我怎样才能发回响应头与Node.js / Express?

我使用res.send ,无论如何,它返回200的状态。我想要设置为不同的数字为不同的响应(错误等)

这是使用express

 res.writeHead(200, {'Content-Type': 'text/event-stream'}); 

http://nodejs.org/docs/v0.4.12/api/http.html#response.writeHead

我假设你正在使用像“Express”这样的库,因为nodejs没有提供res.send方法。

和Express指南一样 ,您可以传递第二个可选参数来发送响应状态,例如:

 // Express 3.x res.send( "Not found", 404 ); // Express 4.x res.status(404).send("Not found"); 

发送添加响应头,可以使用setHeader方法:

 response.setHeader('Content-Type', 'application/json') 

只有 状态方法的状态

 response.status(status_code) 

同时使用writeHead方法:

 response.writeHead(200, {'Content-Type': 'application/json'}); 

在express (4.x)的文档中,res.sendStatus用于发送状态码定义。 正如这里所提到的,每个人都有一个具体的描述。

 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') 

在send()调用之前设置statusCode var

 res.statusCode = 404; res.send(); 

我用这个expression

 res.status(status_code).send(response_body); 

而这个没有明文(普通的http服务器)

 res.writeHead(404, { "Content-Type": "text/plain" }); res.write("404 Not Found\n"); res.end(); 

既然这个问题也提到了Express,你也可以用中间件这样做。

 app.use(function(req, res, next) { res.setHeader('Content-Type', 'text/event-stream'); next(); }); 
Interesting Posts