I am trying to send back a status of 404 to the web client when a request for a non existent record is received.
I'm using Express and MongoDB. Tested with Advanced Rest Client.
Code:
app.get('/api/courses/:id', (req, res) =>
{
dbo.collection("courses").findOne({ id: parseInt(req.params.id) }, function(err, result) {
console.log(result);
if (err) return res.status(400).send(err);
if (!result) { console.log('Null result sending 404'); return res.status(404); }
res.send(result);
});
});
If the client sends a valid id: then the record is returned as expected.
Node Console:
{ _id: 5d23e6a8c922d263376442c1, id: 1, name: 'Course 1' }
Client:
{
"_id": "5d23e6a8c922d263376442c1",
"id": 1,
"name": "Course 1"
}
When the client sends an invalid id: the console shows the message has been sent but the client waits for ever until I stop/reset the server.
Node Console:
null
Null result sending 404
Because you just set status for the response, but you never send back to client anything.
Let's send something to the client.
Example, send a json object
return res.status(404).json({message: 'Null result sending 404'});
instead of return res.status(404);
Related
Im using fcm-node i tried to send a push notification and it perfectly works locally, however when i try to send it using the server, it fails
var message = {
//this may vary according to the message type (single recipient, multicast, topic, et cetera)
to: notificationToken,
notification: {
bla bla
},
};
fcm.send(message, function (err, response) {
console.log("inside");
if (err) {
console.log("Something has gone wrong!", err);
} else {
console.log("Successfully sent with response: ", response);
}
});
Response for server:
Successfully sent with response: {
results: [ { error: [FirebaseMessagingError] } ],
canonicalRegistrationTokenCount: 0,
failureCount: 1,
successCount: 0,
multicastId: 502625035652113000
}
Tried to get the device notified
i want to make Whatsapp bot and integrated to my website. the system send the qr and users scan it through my website and after users scan and connected i want to send a message to the users it had been connected in the same page. but i got this error
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
app.get("/create", (req, res) => {
if (req.query["session"] != undefined && req.query["session"] != "") {
venom.create(
`${req.query['session']}`,
(base64Qr, asciiQR, attempts, urlCode) => {
res.send(`<img src="${base64Qr}"></img>`)
},
(statusSession, session) => {
console.log("Status Session: ", statusSession);
},
{ logQR: false, disableWelcome: true
}).then(() => {
res.write("Connected!");
res.end();
})
} else {
res.json({ status: "Error", messages: "Wrong Parameters" });
}
});
res.send() can only be called once. You cannot call this function 2 or more times for a single request.
I am sending a delete request using axios from my React frontend to node js express backend with mongo DB. Although the data does get deleted from my database but I still get an error 404 Not Found.
Here is React code
axios
.delete(`http://localhost:8000/notes/${id}`)
.then(res => {
console.log("The response is "+res.data)
})
.catch(err => {
console.log("There was an error "+ JSON.stringify(err.response))
});
Here is node js express code app.js
app.delete("/notes/:notesId", cors(), function(req, res) {
const query={_id:req.params.notesId};
console.log("The notes id is "+ query);
Note.findOneAndDelete(query, function(err) {
if(!err) {
console.log("The item got successfully deleted");
res.redirect("/");
} else {
console.log(err)
}
})
})
Please note that the entry gets deleted from my database but i get this error in my browser console :
xhr.js:178 DELETE http://localhost:8000/ 404 (Not Found)
App.jsx:26 There was an error {"data":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot DELETE /</pre>\n</body>\n</html>\n","status":404,"statusText":"Not Found","headers":{"content-length":"142","content-type":"text/html; charset=utf-8"},"config":{"url":"http://localhost:8000/notes/5ee130b65dc5f521acf60f38","method":"delete","headers":{"Accept":"application/json, text/plain, */*"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}
I am trying to hit the complete url till notes id but it is only considering till root
Try modifying the res to send a 200 OK status if the object gets deleted. You could also send a message for your frontend to display in this manner
if(!err) {
res.status(200).json({ message: 'The item got successfully deleted', error: false });
} else {
res.status(500).json({message : 'Oops and error occurred', error : true});
Regardless a simple res.status(200).end(); should suffice as well for your situation.
I am building an Angular 4 and Node application. Once any user registers on the front-end, I am storing their data in the database, and then would like to send them a successful registration email using the nodemailer package.
Here's the Node js code:
router.post('/', function(req, res, next) {
SOME_DATABASE_FUNC() {
if(FAILED_CASE) {
return res.status(500).json({
title: 'An error occurred',
status: 500,
error: error
});
var mailOptions {...}
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
return res.status(500).json({
title: 'An error occurred',
status: 500,
error: error
});
}
console.log('Message', info.messageId, info.response);
return res.status(200).json({
message: 'Emailed successfully',
details: info
});
});
}
}
});
This code works perfectly, but it takes few seconds to send the email, and the user has to wait to show the success response which doesn't seem to fit good. Instead I would like to send it in the background may be as an asynchronous function or like a cron job.
But I am not sure how to transform the code to send it as a job instead of sending and waiting after the database transaction. Please help me out with the issue.
send response outside block of transporter.sendMail. So it will not wait for process of email send to be completed.
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
return res.status(500).json({
title: 'An error occurred',
status: 500,
error: error
});
}
console.log('Message', info.messageId, info.response);
});
return res.status(200).json({
message: 'Emailed successfully',
details: info
});
use Process.nextTick() for sending email
We knew that nodejs request and response is stream and you can do stuff after sending response stream in this way response time will decrease and other stuff will continue asynchronously after sending response to client.
You can send response successfully to client and then you can call send mail function.
I wrote this web Api and wrote first route on root i.e on localhost:3000/ or just / that will return a document from mongodb (I dont know If we can do this that get on "/") like this:
app.get('/data', function(req, res) {
quizz.findOne({ id: 1}, function (err, data) {
if (err) {
console.log(err)
} else {
console.log(data);
res.json(data);
}
})})
and I'm requesting from client like this:
this.http.get('https://localhost:3000/data').map(function (res) {
let body = res.json();
return body.body || {};
}).subscribe((data) => {
console.log(data);
})
but I'm getting this when I'm clicking on button(that actually has method inside which there is request method) Im getting this:
Also tried postman getting this error:
This seems to be like an error connecting to http://localhost:3000/. The response status was 0.