res.end()和res.send()有什么区别?

时间:2015-04-10 07:01:28

标签: node.js express

我是Express.js的初学者,我对这两个关键字感到困惑:res.end()res.send()

它们是相同还是不同?

7 个答案:

答案 0 :(得分:94)

res.send()将发送HTTP响应。它的语法是,

res.send([body])

body参数可以是Buffer对象,String,对象或Array。例如:

res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });

有关详细信息,请参阅this

res.end()将结束回复流程。此方法实际上来自Node核心,特别是response.end()的{​​{1}}方法。它用于在没有任何数据的情况下快速结束响应。例如:

http.ServerResponse

阅读this了解详情。

答案 1 :(得分:58)

我想更加强调res.end()&amp;之间的一些关键差异。 res.send()关于响应标头及其重要性的原因。

<强> 1。 res.send()将检查输出结构并设置标题 相应的信息。

    app.get('/',(req,res)=>{
       res.send('<b>hello</b>');
    });

enter image description here

     app.get('/',(req,res)=>{
         res.send({msg:'hello'});
     });

enter image description here

使用res.end(),您只能回复文字而不会设置“ Content-Type

      app.get('/',(req,res)=>{
           res.end('<b>hello</b>');
      }); 

enter image description here

<强> 2。 res.send()将在响应头

中设置“ETag”属性
      app.get('/',(req,res)=>{
            res.send('<b>hello</b>');
      });

enter image description here

¿为什么这个标签很重要?
ETag HTTP响应头是特定版本资源的标识符。它允许缓存更高效,并节省带宽,因为如果内容未更改,Web服务器不需要发送完整响应。

res.end()不会设置此标头属性

答案 2 :(得分:2)

res.send()的作用是实现 res.write res.setHeaders res.end
它会检查您发送的数据并设置正确的标题,

然后使用res.write将数据流化,最后使用res.end设置请求的结束。

在某些情况下,您需要手动进行操作 例如,如果您要流文件或大型数据集,在这种情况下,您将需要自己设置标题并使用res.write来保持流的流动。

答案 3 :(得分:1)

res是从OutgoingMessage扩展的HttpResponse对象。 res.send调用由OutgoingMessage实现的res.end发送HTTP响应和关闭连接。我们看到代码here

答案 4 :(得分:0)

res.send 用于向客户端发送响应,其中 res.end 用于结束您正在发送的响应。

res.send 自动调用 res.end 所以你不必在 res.send

之后调用或提及它

答案 5 :(得分:0)

除了优秀的答案,我想在这里强调什么时候使用 res.end() 以及什么时候使用 res.send() 这就是为什么我最初登陆这里并没有找到解决方案。

答案很简单

res.end() 用于在不发送任何数据的情况下快速结束响应。

一个例子是在服务器上启动一个进程

app.get(/start-service, (req, res) => {
   // Some logic here
   exec('./application'); // dummy code
   res.end();
});

如果您想在响应中发送数据,则应改用 res.send()

app.get(/start-service, (req, res) => {
   res.send('{"age":22}');
});

在这里你可以阅读更多

答案 6 :(得分:0)

res.end() 函数用于结束响应过程。 res.send() 函数是 res.write()res.setHeaders()res.end() 的组合。

相关问题