Sha*_*oon 25 node.js response-headers express
我正在使用res.send,无论如何,它返回200的状态.我想为不同的响应设置该状态为不同的数字(错误等)
这是用的 express
cho*_*ovy 30
res.writeHead(200, {'Content-Type': 'text/event-stream'});
Run Code Online (Sandbox Code Playgroud)
http://nodejs.org/docs/v0.4.12/api/http.html#response.writeHead
Z. *_*lah 26
要在发送之前添加响应标头,可以使用setHeader方法:
response.setHeader('Content-Type', 'application/json')
Run Code Online (Sandbox Code Playgroud)
该状态只能用状态的方法:
response.status(status_code)
Run Code Online (Sandbox Code Playgroud)
两者同时使用writeHead方法:
response.writeHead(200, {'Content-Type': 'application/json'});
Run Code Online (Sandbox Code Playgroud)
Nic*_*can 16
我假设您正在使用像"Express"这样的库,因为nodejs不提供res.send方法.
与Express指南中一样,您可以传入第二个可选参数来发送响应状态,例如:
// Express 3.x
res.send( "Not found", 404 );
// Express 4.x
res.status(404).send("Not found");
Run Code Online (Sandbox Code Playgroud)
既然问题也提到Express,你也可以这样使用中间件.
app.use(function(req, res, next) {
res.setHeader('Content-Type', 'text/event-stream');
next();
});
Run Code Online (Sandbox Code Playgroud)
您应该为您的目的使用setHeader方法和status方法。
解决方案:
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);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74117 次 |
| 最近记录: |