如何在 POSTMAN 上获得与浏览器相同的响应行为?

How to get response behaviour same on POSTMAN as like Browser?

下面是我的代码:

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 访问浏览器,那么在访问 URL 时它会在浏览器上显示 First,两秒后它会显示 Done。这很好。

但是当我在 POSTMAN 上尝试这个时,为什么它显示

First
Done

在一起。任何人都可以解释它的原因吗?或者这是否也可能在邮递员身上获得相同的响应行为?

在您的代码中,您使用 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 值生成循环)