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