Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 323
Shamoon Avatar asked Oct 06 '11 14:10

Shamoon


People also ask

How do I send response back in node js?

setHeader('Content-Type', 'text/html'); this line will set the format of response content o text/html. write() function method on response object can be used to send multiple lines of html code like below. res. write('<html>'); res.

How do you send a header in node js?

We will use request. setHeader() to set header of our request. The header tells the server details about the request such as what type of data the client, user, or request wants in the response. Type can be html , text , JSON , cookies or others.

How do you send a response header?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

How do I get response headers in node js?

To get HTTP headers with Node. js, we can use the res. headers properties. const http = require("http"); const options = { method: "HEAD", host: "example.com", port: 80, path: "/", }; const req = http.


2 Answers

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'}); 
like image 112
Bernardo Dal Corno Avatar answered Sep 18 '22 12:09

Bernardo Dal Corno


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

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

like image 44
chovy Avatar answered Sep 20 '22 12:09

chovy