前端旧约

今天做别人不愿意做的事, 明天做别人不能做的事

res.end 和 res.send 的区别

简单来说就是 如果服务器端没有数据返回到客户端 那么就可以用 res.end, 但是 如果 服务器端有数据返回到客户端 这个时候必须用res.send ,不能用 res.end(会报错) 。

官方说明

  • res.end() 终结响应处理流程。
  • res.send() 发送各种类型的响应。

1)res.end([data] [,encoding])**

结束响应过程。这个方法实际上来自Node核心,特别是http.ServerResponse的response.end()方法。

用于在没有任何数据的情况下快速结束响应。如果需要响应数据,请使用res.send()和res.json()等方法。

res.end();res.status(404).end();

2)res.send([body])**

发送HTTP响应。

所述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' });

此方法为简单的非流式响应执行许多有用的任务:例如,它自动分配Content-Length HTTP响应头字段(除非先前已定义)并自动提供HEAD和HTTP缓存支持。

当参数是Buffer对象时,该方法将Content-Type 响应头字段设置为“application / octet-stream”,除非先前定义如下所示:

res.set('Content-Type', 'text/html');res.send(new Buffer('<p>some html</p>'));

当参数为String,该方法将设置Content-Type为“text / html”:

res.send('<p>some html</p>');

当参数是Array或Object,Express以JSON表示响应:

res.send({ user: 'tobi' });res.send([1,2,3]);

总结

  1. 参数类型的区别:
  • res.end() 参数为: a Buffer object / a String
  • res.send() 参数为: a Buffer object / a String / an object / an Array
  1. 发送服务器内容不同
  • res.end() 只接受服务器响应数据,如果是中文则会乱码
  • res.send() 发送给服务端时,会自动发送更多的响应报文头,其中包括 Content-Tpye: text/html; charset=uft-8,所以中文不会乱码

posted on 2020-03-31 09:31  前端旧约  阅读(3372)  评论(0编辑  收藏  举报

导航