Express.js上可以以数据块形式发送响应吗?我已经try 过(online demo):

const express = require('express');
const app = express();
const port = 3111;

const sleep = (ms) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

app.get('/', async (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  // flush to enable stream
  res.flushHeaders();
  res.write('[');
  for (let i = 1; i <= 1000; i++) {
    res.write(JSON.stringify(`data ${i}`));
    if (i + 1 <= 1000) {
      res.write(',');
    }
    await sleep(1);
  }
  res.write(']');
  res.end();
});

app.listen(port, () => {
  console.log(`App is live at http://localhost:${port}`);
});

但在Google Chrome和Postman上,只有在呼叫res.end()时才会显示响应

推荐答案

有一些考虑

  1. 您应该为application/stream+json等流添加正确的Content-Type
  2. 请记住,浏览器和一些HTTP客户端可能会缓冲响应(它们不会在块到达时显示,而是等到收到整个响应),因此您可能需要考虑使用JavaScript来处理响应.
  3. 您不需要res.flushHeaders(),因为当您开始编写响应正文时,Express会自动处理它
import express from "express";
const app = express();

const sleep = (ms) => {
    return new Promise((resolve) => setTimeout(resolve, ms));
};

app.get('/stream', async (_req, res) => {
    res.setHeader('Content-Type', 'application/stream+json');

    res.write('[');
    for (let i = 1; i <= 1000; i++) {
        res.write(JSON.stringify(`data ${i}`));
        if (i < 1000) {
            res.write(",");
        }
        await sleep(1); // Simulates a delay
    }
    res.write(']');
    res.end();
});

const port = 3000;
app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
});

Javascript相关问答推荐

jsfat的黑色画布输出

如何在pixi js中画一条简单的线

将未等待的未处理的错误promise 转变为警告@ changeTicksAndRejections(由当时的抛出错误创建)

在Chart.js 4.4.2中移动到不同大小的容器时,图表不会调整大小

为什么JavaScript双边字符串文字插值不是二次的?

Next.js Next/Image图像隐含性有任何类型-如何修复?

TypScript界面中的Infer React子props

从mat—country—select获取整个Country数组

使搜索栏更改语言

嵌套异步JavaScript(微任务和macrotask队列)

为什么这个JS模块在TypeScript中使用默认属性导入?""

编辑文本无响应.onClick(扩展脚本)

如何发送从REST Api收到的PNG数据响应

第二次更新文本输入字段后,Reaction崩溃

使用getBorbingClientRect()更改绝对元素位置

未捕获的运行时错误:调度程序为空

不协调嵌入图片

本地损坏的Java脚本

在JavaScript中将Base64转换为JSON

无法使用npm install安装react-dom、react和next