首页 > 解决方案 > 如何在 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:3000then on access URL 访问浏览器,它会显示First在浏览器上,两秒钟后会显示Done。这很好。

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

首先
完成

一起。谁能解释它的原因?或者这是否可能在邮递员上获得相同的响应行为?

标签: javascriptnode.jsasynchronouspostmansettimeout

解决方案


在您的代码中,您将块发送回客户端,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值来生成一个循环)


推荐阅读