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:03

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'});
查看更多
劳资没心,怎么记你
3楼-- · 2020-06-30 14:06
res.writeHead(200, {'Content-Type': 'text/event-stream'});

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

查看更多
霸刀☆藐视天下
4楼-- · 2020-06-30 14:08

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();
});
查看更多
神经病院院长
5楼-- · 2020-06-30 14:10

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);
  }
});
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-06-30 14:12

set statusCode var before send() call

res.statusCode = 404;
res.send();
查看更多
神经病院院长
7楼-- · 2020-06-30 14:16

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