Shamoon
Shamoon

Reputation: 43639

How can I send back response headers with Node.js / Express?

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

Upvotes: 43

Views: 144956

Answers (8)

Naveen Kumar V
Naveen Kumar V

Reputation: 2829

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

Upvotes: 8

mbokil
mbokil

Reputation: 3340

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

Upvotes: 9

Bernardo Dal Corno
Bernardo Dal Corno

Reputation: 2088

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

Upvotes: 59

Nican
Nican

Reputation: 7945

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

Upvotes: 15

cs04iz1
cs04iz1

Reputation: 1815

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

Upvotes: 4

fuelusumar
fuelusumar

Reputation: 797

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

Upvotes: 3

Yura
Yura

Reputation: 1823

set statusCode var before send() call

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

Upvotes: 4

chovy
chovy

Reputation: 75854

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

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

Upvotes: 41

Related Questions