javascript - 如何在 POSTMAN 上获得与浏览器一样的响应行为?
问题描述
下面是我的代码:
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/html');
res.write("First \n");
setTimeout(() => {
res.end("Done");
},2000);
});
app.listen(3000, () => {
console.log("Server is running on port 3000")
})
现在,如果我使用http://localhost:3000
then on access URL 访问浏览器,它会显示First
在浏览器上,两秒钟后会显示Done
。这很好。
但是当我在 POSTMAN 上尝试这个时,为什么它会显示
首先
完成
一起。谁能解释它的原因?或者这是否可能在邮递员上获得相同的响应行为?
解决方案
在您的代码中,您将块发送回客户端,res.write
这些块将在它们到达浏览器时被渲染,从而导致您描述的延迟效果。
然而,目前 Postman 不支持这种分块,它会一直等到收到响应结束的信号(来自res.end
)。基本上它会等待整个响应,然后再对其进行处理。
这可能会在即将发布的 Postman 版本中发生变化:Github
编辑:
使用 Fetch API 可以像这样访问这些块:
fetch("/")
// Retrieve its body as ReadableStream
.then(response => response.body)
.then(body => {
const decoder = new TextDecoder('utf-8');
const reader = body.getReader();
reader.read().then(({ done, value }) => console.log(decoder.decode(value)));
reader.read().then(({ done, value }) => console.log(decoder.decode(value)));
});
(除了你会使用这个done
值来生成一个循环)
推荐阅读
- azure-iot-edge - OPC Publisher 和消息路由
- javascript - 为什么 getTime() 返回不一致的值?
- c# - 使用 C# 删除 SFTP 服务器中 zip 文件中的文件
- swift - 我无法在表格视图中插入新行
- typescript - 像控制台记者一样设置 Jasmine
- c# - 在解析对 C# 对象的 Json 响应时跳过 Nullable int
- angular - Ng-Select - 使用 ControlValueAccessor 接口选择/取消选择自定义组件中的所有项目
- python - Pandas 基于 str.find 切片字符串作为开始和停止的位置
- jasmine - 量角器 - 等待换班
- html - 一个链接应保持按下状态,直到您单击另一个链接