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.
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.
Answer is "Add a new header and value"
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.
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-readablestatusMessage
as the second argument.
var body = "hello world"; response.writeHead(200, { "Content-Length": body.length, "Content-Type": "text/plain", "Set-Cookie": "type=ninja" });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With