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

Viewed 145

Here below is my code:

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")
})

Now, If I access the browser using http://localhost:3000 then on access URL it shows First on the browser and after two seconds it shows Done. which is fine.

but when I try this on POSTMAN why it shows

First
Done

together. Can anyone explain the reason for it? Or Is this possible or not to get the same behaviour of response on postman as well?

1 Answers

In your code you are sending chunks back to client with res.write these chunks will get rendered as they arrive by the browser resulting in the delay effect you describe.

Currently however Postman does not support this chunking and it waits until it gets the signal the response has ended (from res.end). Basically it waits for the entire response before doing something with it.

This might change in upcoming versions of Postman: Github

Edit:

Using the Fetch API those chunks can be accessed like this:

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)));
  });

(except that you would use the done value to generate a loop)

Related