Reading response from Node JS Server - javascript

I am working on a program where a specific Java file will be compiled at the Server side and if there is any error in compiling, I will capture the error information and send it back to the client side. However, I have tried many ways to read the JSON Object but to no avail.
So my question is why was I not able to read the error string sent by the server at the client side? I am current using res.data.err to read my error response.
Server Side Code
var cmd=require('node-cmd');
exports.compileTest = function(req,res){
console.log(req.body.data.fileName);
var file = req.body.data.fileName;
var output = "";
output = cmd.get(
'javac solutionTest/'+file,
function(err, data, stderr){
if (err) {
console.log(err);
res.json({ state : 0 ,err});
}
else
res.json({ state : 1});
}
);
}
Client Side Code
$scope.compileSol = function(){
$http.post('/testRun', { data : { fileName : $scope.solutionFileName.name}
}).then(function(res){
if(res.data.state==0){
alert(res.data.err);
}
}).catch(function(error){
});
}
Below is the error I wanted to send over to the web browser

I suppose your err variable that you are sending from your server is a JSON object that has for key: err. If not, you can consider modifying it, the way I do below.
if (err) {
console.log(err);
res.json({ state : 0 ,err: err});
}
else
res.json({ state : 1});
}
The object response on your client side should have the same form as how you sent it. In the way you are sending it from your server, it should be this way you can access it client side:
if(res.state==0){
alert(res.err);
}
}).catch(function(error){
});

My mistake lies in assume err is the exact error output by the server.
Solution is to convert it to String and then send it over.
var cmd=require('node-cmd');
exports.compileTest = function(req,res){
console.log(req.body.data.fileName);
var file = req.body.data.fileName;
var output = "";
output = cmd.get(
'javac solutionTest/'+file,
function(err, data, stderr){
if (err) {
console.log(err);
//added this line
err = err.toString();
res.json({ state : 0 ,err:err});
}
else
res.json({ state : 1});
}
);
}

Related

How to obtain realtime message from socket. io in cordova app?

I am setting up chat functionality in a Cordova project using socket.io
However, I am unable to load the message at realtime.
On the client side of my Cordova app, I have written the code for the send message button as below:
$('#send').click(function() {
if ($('#msg_inp').val()) {
var data = {
fromId: fromId,
toId: toId,
message: $('#msg_inp').val()
}
var child = `<div class="media"><div class="media-body media-color-right">`
+ (data.message) + `</div></div> `
$('#chatbox').append(child);
$('#msg_inp').val('');
socket.emit('chatting',data);
}
}
);
I am emitting the data to the server side to store the message in the database.
The code on the server side is this:
socket.on('chatting', function (data) {
userM.findSenderAndReceiver(data.fromId, data.toId, function (err, result) {
console.log(result);
if (err) {
console.log(err);
throw err;
} else {
userM.insertMessages(data, function (err, result) {
if (err) {
throw err;
console.log(err);
}
});
console.log(data);
data.chattingwith = result.from.username;
data.chattingwithId = result.from.id;
data.from_image_url = result.from.image_url;
data.to_image_url = result.to.image_url;
console.log(data);
socket.broadcast.to(result.to.socketID).emit('chatting', data);
}
});
});
On the server side after storing the message (as you can see from the above code), I am emitting the data to the receiver socketID to display the chat in the receiver's chat window at realtime.
However, I am unable to fetch the broadcasted message on the client side.
I was trying it as :
socket.on('chatting',function(data){
console.log(data) // -> This data doesn't get displayed.
});
So, how should I handle the broadcasted data from the socket to display the message at realtime?

How to watch changestream in mongoDB and send the updates to an ajax call?

I'm using the new feature of MongoDB 3.6 watch() in order to send updates of the database from the node server to ajax in the client side.
I created a webservice queried periodically by an ajax call. Between two successive ajax calls, i want the second one to get all the updates that occurred in the mean time. I know that i have to resume the change stream as shown in the official documentation here : https://docs.mongodb.com/manual/changeStreams/#resume-a-change-stream . However i didn't find out how to apply this to my specific needs, by that i mean, in which callback can i process my data and send it to the webservice response ?
Here is a part of my server side code : server.js
const pipeline = [
{
$match : {
"operationType" : "insert"
,
"fullDocument.T" : { "$exists":true}
}
},
{
$project: { "fullDocument.ts": 1,
"fullDocument.T":1}
}
];
function getLiveData(handler){
console.log("in getLiveData");
var liveArray=[];
var resumeToken;
const changeStream = dbObject.collection('status').watch(pipeline);
changeStream.hasNext(function(err, change) {
if (err) return console.log(err);
expect(err).to.equal(null);
expect(change).to.exist;
console.log("in changeStream.hasNext");
changeStream.next(function(err, change) {
if (err) return console.log(err);
expect(err).to.equal(null);
console.log("in changeStream.next");
resumeToken = change._id;
expect(change._id).to.exist;
expect(changeStream.resumeToken).to.exist;
changeStream.close(function(err) {
if (err) return console.log(err);
expect(err).to.equal(null);
console.log("in changeStream.close");
const newChangeStream = dbObject.collection('status').watch({ resumeAfter: resumeToken });
newChangeStream.next(function(err, next) {
if (err) return console.log(err);
expect(err).to.equal(null);
expect(next).to.exist;
console.log("in newChangeStream.next");
//my own code
newChangeStream.on("change", function(change) {
console.log('in change stream, change : ',change);
liveArray.push([change.fullDocument.ts, change.fullDocument.T]);
var response = {
"liveArray" : liveArray
};
console.log("from getLiveData : " , response);
handler(response);
});
//my own code
// Since changeStream has an implicit seession,
// we need to close the changeStream for unit testing purposes
newChangeStream.close();
});
});
});
});
}
webservice part :
app.get("/liveDataRequest", function(req, res){
getLiveData(function(data){
console.log("in handler", data);
res.status(200).send(data);
});
And here is the console log, as we can see, the part where i process my data never gets called :
in getLiveData
in changeStream.hasNext
in changeStream.next
in changeStream.close
in newChangeStream.next
in getLiveData
in changeStream.hasNext
in changeStream.next
in changeStream.close
in newChangeStream.next

Send HTTP.call Json

I have problems sending a json that will be verified by another server, where then I will get a response from that process has been exist. I'm using HTTP.call, but I have not gotten so far any results in when to functionality.
Already do the tests with postman and everything works me correctly.
Here is a copy of code:
// client side event click button
var jsonStr = JSON.stringify(jsonOBJ);
Meteor.call("Json", jsonStr, function(error, result){
if(error){
console.log("error", error);
}
if(result){
console.log(resul);
}
});
///server side
Json(JsonStr) {
var options = {
data: JsonStr,
headers: {
'content-type': 'application/json'
}
}
try {
var url = "https://api.xxxxxxxxx.com/xxxxxxx-api/4.0/xxxxxx.cgi";
var result = HTTP.call('POST', url, options )
return result;
} catch (err) {
console.log(err)
}
}
//I must receive something like
{
"code": "SUCCESS",
"error": null,
"transactionResponse": {
....
....
....
}
}
That's the answer I'm getting from the server
"{"code":"ERROR","error":"Invalid request format","result":null}"
Fixed problem is when using var str = JSON.stringify (jsonOBJ); From the client and it passes through Meteor.call() when it receives the meteor methods on the server does not arrive with the correct format so the solution is to pass the jsonObj from the client without giving the format and to be received on the server if apply The JSON.stringify (jsonOBJ)

Done function never called after $.ajax

I'm a bit new to all this (including Javascript callbacks and ES6). I'm using NodeJS + Express + MongoDB.
I'm calling an Ajax function to update an item and the success Ajax call is never done.
Here is my Ajax call (called from React)
editBug : function(bug){
console.log('about to edit bug with these values',bug);
$.ajax({
url:'/api/bugs',
method: 'PUT',
data:bug
})
.done((jqxhr) => {
console.log('succcess while editing the bug');
this.setState({successVisible : true});
})
.fail((jqxhr) => {
console.log('error : ' + jqxhr);
})
},
Here is my API function:
app.put('/api/bugs',function(req,res){
//console.log('req',req);
console.log('query string : ',req.query);
console.log('query params : ',req.params);
console.log('query body: ',req.body);
let id = new ObjectID(req.body._id);
req.body._id = new ObjectID(req.body._id);
db.collection('bugs').replaceOne(
{_id:id},
req.body,
function(err,result){
assert.equal(err,null);
console.log('Successfull replace!');
res.status(200);
}
);
});
The Successfull replace! log is correctly shown on the server side.
The about to edit bug with these values is correctly shown on the front side. But the succcess while editing the bug log is not shown on front end and it seems .done call is never executed.
The problem is that you are not sending any response back to the browser on node side. Try the following snippet and you should be good to go
Also, I'd like to point out that you should handle the errors. While updating the bugs if something goes wrong, the best practice would be to inform the browser with the 500 status code indicating that the intended action failed. I've added this aspect in the snipped below
app.put('/api/bugs', function(req, res) {
//console.log('req',req);
console.log('query string : ', req.query);
console.log('query params : ', req.params);
console.log('query body: ', req.body);
let id = new ObjectID(req.body._id);
req.body._id = new ObjectID(req.body._id);
db.collection('bugs').replaceOne({
_id: id
},
req.body,
function(err, result) {
if (err) {
console.log('Failed replace');
res.status(500).end(); // <- We set the response status code and end the request
} else {
assert.equal(err, null);
console.log('Successfull replace!');
res.status(200).end(); // <- We set the response status code and end the request
}
}
);
});
Don't you need to end your response object on the Node.js side?
Try adding res.end(); or any kind of response to your response object.
Also, you can use chrome's (or any other browser's) network tab to actually see how your AJAX requests end up, to see if they hang or finish.

How to handle error in Angular Controller from MongoDB database update/delete in Express?

I am trying to figure out how to handle an error when deleting or updating a document in MongoDB in Angular JS?
I have the following route in Node/Express:
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
//log the reason for the error
res.status(code || 500).json({
"error": message
});
}
app.delete("/polls/:id", auth, function(req, res) {
db.collection(POLLS_COLLECTION).deleteOne({
_id: new ObjectID(req.params.id), userID: req.user.id
//userID must match the req.user.id from Passport to make sure the poll belongs to the user
}, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to delete poll");
} else {
res.status(204).end();
}
});
});
The following in an Angular JS controller:
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
alert("Error deleting poll");
console.log(response);
})
};
deleteThisPoll in the controller calls a deletePoll service that sends a a request to the route:
this.deletePoll = function(pollId){
var url = "/polls/" + pollId;
return $http.delete(url);
};
What I want is to alert "Error deleting poll" from the Angular controller when the database delete is not executed (because for example user is not authenticated or the poll doesnt belong to the user) and "Poll Deleted" when the delete was successfull.
However: the error callback is never used and the app always alerts "Poll deleted!" no matter if the document was deleted or not deleted.
Doesn't my route send an error response when the delete was not executed and will it not hit my Angular error callback?
You can do like code below
Put this HTML code where you want to show error message :
<div style="color:red;">
{{error}}
</div>
In your angular js controller :
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
$scope.error="Any error message you like to show";
console.log(response);
})
};
If your API return an error. you can catch it like this :
Polls.deletePoll($routeParams.pollId).then(function(response) {
//SUCCESS CODE
}).catch(function(error) {
//NOTIFY ERROR
//NotifyService.display(error);
console.log(error);
});
thanks guys. I found out that MongoDB for some reason always returns a result object even when there was no delete/update. I solved this by checking for the result.deletedCount propety that is set to 1 or 0. Like so:
if(err){
res.status(500).end();
}
if(result.deletedCount === 0){
res.status(404).end();
//error handling in Angular error callback
} else {
res.status(204).end();
//error handling in Angular success callback
}
});
});
this makes sure that not always a 204 is send whether or not the delete was successfull.

Categories

Resources