Express中res.end() res.send() 及res.send()

简单来说,如果服务器端没有数据返回到客户端,使用res.end(),否则需要用res.send()

express响应中用到常用三种API:

  • res.send()
  • res.json()
  • res.end()

1.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' });

   三种不同参数 express 响应时不同行为:

      1.1当参数是Buffer对象

         该方法将Content-Type响应头字段设置为" application/octet-stream ",除非之前定义如下:

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

     1.2 当参数是String

         该方法设置header 中Content-Type为“text / html”:

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

    1.3 当参数是Arrayor 或 Object

       Express以JSON表示响应,该方法设置header 中Content-Type为“text / html”

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

2.res.json([body]) 

     发送一个JSON响应。此方法发送一个响应(具有正确的内容类型),该响应是使用JSON.stringify()转换为JSON字符串的参数

     该参数可以是任何JSON类型,包括对象、数组、字符串、布尔值、数字或null,还可以使用它将其他值转换为JSON

3.res.end([data] [,encoding])

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

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

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

4 总结

    1.参数类型的区别:

  • res.send() 参数为: a Buffer object / a String / an object / an Array
  • res.json()  参数为:任何JSON类型
  • res.end()  参数为: a Buffer object / a String

    2.场景使用:

        用于快速结束没有任何数据的响应,使用res.end()。
        响应中要发送JSON响应,使用res.json()。
        响应中要发送数据,使用res.send() ,但要注意header ‘content-type’参数。
        如果使用res.end()返回数据非常影响性能。

参考官方文档 

  • 11
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值