Javascript response.setHeader 和 response.writeHead 的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28094192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:12:43  来源:igfitidea点击:

Difference between response.setHeader and response.writeHead?

javascriptnode.js

提问by cYn

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.

在我的应用程序中,我让我的 Nodejs 服务器发送一个 JSON 响应。我找到了两种方法来做到这一点,但我不确定有什么区别。

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.

两种方式都有效,我只是想知道两者之间有什么区别以及何时应该使用一种而不是另一种。

回答by zero298

response.setHeader()allows you only to set a singularheader.

response.setHeader()只允许您设置单个标题。

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

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. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessageas the second argument.

向请求发送响应标头。状态码是一个 3 位的 HTTP 状态码,如404. 最后一个参数headers是响应标头。可选地,可以将人类可读的statusMessage作为第二个参数。

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