[英]Difference between response.setHeader and response.writeHead?
In my application, I have my Nodejs server send a JSON response.在我的应用程序中,我让我的 Nodejs 服务器发送一个 JSON 响应。 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.两种方式都有效,我只是想知道两者之间有什么区别,以及何时应该使用一种而不是另一种。
response.setHeader()
allows you only to set a singular header. response.setHeader()
只允许您设置单个标题。
response.writeHead()
will allow you to set pretty much everything about the response head including status code, content, and multiple headers. response.writeHead()
将允许您设置有关响应头的几乎所有内容,包括状态代码、内容和多个标头。
Consider the NodeJS docs:考虑 NodeJS 文档:
response.setHeader(name, value) response.setHeader(名称,值)
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])) response.writeHead(statusCode[, statusMessage][, headers]))
Sends a response header to the request.
向请求发送响应标头。 The status code is a 3-digit HTTP status code, like
404
.状态码是一个 3 位的 HTTP 状态码,如
404
。 The last argument,headers
, are the response headers.最后一个参数
headers
是响应头。 Optionally one can give a human-readablestatusMessage
as the second argument.可以选择提供一个人类可读的
statusMessage
作为第二个参数。
var body = "hello world";
response.writeHead(200, {
"Content-Length": body.length,
"Content-Type": "text/plain",
"Set-Cookie": "type=ninja"
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.