response.setHeader和response.writeHead之间的区别? [英] Difference between response.setHeader and response.writeHead?
问题描述
在我的应用程序中,我让我的Nodejs服务器发送JSON响应。我找到了两种方法,但我不确定它们之间的差异。
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.
一种方法是
var json = JSON.stringify(result.rows);
response.writeHead(200, {'content-type':'application/json', 'content-length':Buffer.byteLength(json)});
response.end(json);
我的另一种方式是
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()
允许你只设置单数标题。
response.writeHead()
会允许你设置响应头的所有内容,包括状态代码,内容和多个标题。
response.writeHead()
will allow you to set pretty much everything about the response head including status code, content, and multiple headers.
考虑API:
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 if you need 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,[reasonPhrase],[header])
向请求发送响应标头。状态代码是一个3位数的
HTTP状态代码,如404.最后一个参数headers是
响应头。可选地,可以给出人类可读的
reasonPhrase作为第二个参数。
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 reasonPhrase as the second argument.
var body = "hello world";
response.writeHead(200, {
"Content-Length": body.length,
"Content-Type": "text/plain",
"Set-Cookie": "type=ninja"
});
这篇关于response.setHeader和response.writeHead之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!