How can I send back response headers with Node.js

2020-06-30 13:43发布

问题:

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

回答1:

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

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



回答2:

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:

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");


回答4:

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:

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:

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


回答7:

set statusCode var before send() call

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


回答8:

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();