I'm using res.send
and no matter what, it returns status of 200. I want to set that status to different numbers for different responses (Error, etc)
This is using express
I'm using res.send
and no matter what, it returns status of 200. I want to set that status to different numbers for different responses (Error, etc)
This is using express
res.writeHead(200, {'Content-Type': 'text/event-stream'});
http://nodejs.org/docs/v0.4.12/api/http.html#response.writeHead
For adding response headers before send, you can use the setHeader method:
response.setHeader('Content-Type', 'application/json')
The status only by the status method:
response.status(status_code)
Both at the same time with the writeHead method:
response.writeHead(200, {'Content-Type': 'application/json'});
res.writeHead(200, {'Content-Type': 'text/event-stream'});
http://nodejs.org/docs/v0.4.12/api/http.html#response.writeHead
I'll assume that you're using a library like "Express", since nodejs doesn't provide ares.send
method.
As in the Express guide, you can pass in a second optional argument to send the response status, such as:
// Express 3.x
res.send( "Not found", 404 );
// Express 4.x
res.status(404).send("Not found");
Since the question also mentions Express you could also do it this way using middleware.
app.use(function(req, res, next) {
res.setHeader('Content-Type', 'text/event-stream');
next();
});
You should use setHeader method and status method for your purpose.
SOLUTION:
app.post('/login', function(req, res) {
// ...Check login credentials with DB here...
if(!err) {
var data = {
success: true,
message: "Login success"
};
// Adds header
res.setHeader('custom_header_name', 'abcde');
// responds with status code 200 and data
res.status(200).json(data);
}
});
set statusCode var before send() call
res.statusCode = 404;
res.send();
In the documentation of express (4.x) the res.sendStatus is used to send status code definitions. As it is mentioned here each has a specific description.
res.sendStatus(200); // equivalent to res.status(200).send('OK')
res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
i use this with express
res.status(status_code).send(response_body);
and this without express (normal http server)
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.write("404 Not Found\n");
res.end();
© 2022 - 2024 — McMap. All rights reserved.
res.send(404, "Not found");
The old way still works, but I would change it to keep up with the times. – Commonality