response.setHeader和response.writeHead之间的区别?

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

一种方法是

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); 

两种方式都有效,我只是想知道两者有什么区别,什么时候应该使用这两者。

response.setHeader()允许你只设置一个单独的头。

response.writeHead()将允许你设置几乎所有的响应头,包括状态码,内容和多个头。

考虑一下API:

response.setHeader(名称,值)

为隐式标头设置一个标头值。 如果这个头文件已经存在于待发送头文件中,它的值将被replace。 如果您需要发送具有相同名称的多个标头,请在此使用string数组。

 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],[headers])

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

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