Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between response.setHeader and response.writeHead?

In my application, I have my Nodejs server send a JSON response. I found two ways to do this but I'm not sure what the differences are.

One way is

var json = JSON.stringify(result.rows); response.writeHead(200, {'content-type':'application/json', 'content-length':Buffer.byteLength(json)});  response.end(json); 

And my other way is

var json = JSON.stringify(result.rows); response.setHeader('Content-Type', 'application/json'); response.end(json); 

Both ways work and I'm just wondering what the difference is between the two and when I should use one over the other.

like image 967
cYn Avatar asked Jan 22 '15 16:01

cYn


People also ask

What does Response setHeader do?

setHeader() Method. The response. setHeader(name, value) (Added in v0. 4.0) method is an inbuilt application programming interface of the 'http' module which sets a single header value for implicit headers.

What is the meaning of response setHeader XYZ ABC );?

Answer is "Add a new header and value"

What is the use of response setHeader in Java?

setHeader. Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.


1 Answers

response.setHeader() allows you only to set a singular header.

response.writeHead() will allow you to set pretty much everything about the response head including status code, content, and multiple headers.

Consider the NodeJS docs:

response.setHeader(name, value)

Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name.

var body = "hello world"; response.setHeader("Content-Length", body.length); response.setHeader("Content-Type", "text/plain"); response.setHeader("Set-Cookie", "type=ninja"); response.status(200); 

response.writeHead(statusCode[, statusMessage][, headers]))

Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.

var body = "hello world"; response.writeHead(200, {     "Content-Length": body.length,     "Content-Type": "text/plain",     "Set-Cookie": "type=ninja" }); 
like image 62
zero298 Avatar answered Sep 25 '22 01:09

zero298