在 express 中 res.send 和 res.write 有什么区别?

新手上路,请多包涵

我是 express.js 的初学者,我想了解 res.sendres.write 之间的区别?

原文由 P G 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

res.send

  • res.send 仅在 Express.js 中。

  • 为简单的非流式响应执行许多有用的任务。

  • 能够自动分配 Content-Length HTTP 响应头字段。

  • 能够提供自动 HEAD 和 HTTP 缓存新鲜度支持。

  • 实用说明

    • res.send 只能调用一次,因为它相当于 res.write + res.end()
    • 例子:
     app.get('/user/:id', function (req, res) {
        res.send('OK');
    });
    
    
    

更多细节:


res.write

  • 可以多次调用以提供身体的连续部分。
  • 例子:
   response.write('<html>');
  response.write('<body>');
  response.write('<h1>Hello, World!</h1>');
  response.write('</body>');
  response.write('</html>');
  response.end();

更多细节:

原文由 Omal Perera 发布,翻译遵循 CC BY-SA 4.0 许可协议

res.send is equivalent to res.write + res.end So the key difference is res.send can be called only once where as res.write can be called multiple times followed by一个 res.end

但除此之外 res.send 是Express的一部分。它可以自动检测响应头的长度。但是 res.send() 可能会出现内存峰值,在大文件的情况下,我们的应用程序会在两者之间挂起。

原文由 Keerti 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题