本文介绍了response.setHeader和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:



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



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

这篇关于response.setHeader和response.writeHead之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 12:52