How can I send back response headers with Node.js

2020-06-30 13:50发布

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

8条回答
疯言疯语
2楼-- · 2020-06-30 14:19

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')
查看更多
劫难
3楼-- · 2020-06-30 14:24

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();
查看更多
登录 后发表回答