快速路由内的 WebSocket 仅适用于第一次调用

编程入门 行业动态 更新时间:2024-10-04 11:15:44

快速路由内的 WebSocket 仅<a href=https://www.elefans.com/category/jswz/34/1770480.html style=适用于第一次调用"/>

快速路由内的 WebSocket 仅适用于第一次调用

我有一个 expressJS 服务器,我想在其中调用一个 WebSocket(我使用 ws 包)。

这是我在服务器端所做的:

import express from 'express';
import { WebSocketServer } from 'ws';

const app = express();

const server = app.listen(3000);

const wss = new WebSocketServer({ server });

// Set the wss to be able to retrieve it in the route
app.set('wss', wss);

app.get('/download', (req, res) => {
  // Retrieve the WebSocket server
  const wss = req.app.get('wss');
  wss.on('connection', async (ws) => {
    ws.send('hello world');
    // Do some async stuff here to gather data and send some messages
    const fileContents = Buffer.from(myData);

    const readStream = new stream.PassThrough();
    readStream.end(fileContents);

    res.set('Content-disposition', `attachment; filename=test.csv`);
    res.set('Content-Type', 'text/csv');

    readStream.pipe(res);
    ws.close()
  })
})

在我的客户中:

axios.get('http://'+ window.location.host +'/download', {
  responseType: 'blob',
}).then(response=>{
  // create file link in browser's memory
  const href = URL.createObjectURL(response.data);

  // create "a" HTML element with href to file & click
  const link = document.createElement('a');
  link.href = href;
  link.setAttribute('download', `file.csv`); 
  //or any other extension
  document.body.appendChild(link);
  link.click();

  // clean up "a" element & remove ObjectURL
  document.body.removeChild(link);
  URL.revokeObjectURL(href);
})
const ws = new WebSocket('ws://' + window.location.host);

ws.addEventListener('message', function(m) {
  // Do some stuff with messages
})

这在第一次调用

/download
时正常工作。但是第二次(当我刷新客户端的页面时),我在服务器中收到以下错误并且服务器崩溃:

node:internal/errors:478
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

快递似乎考虑了第一个请求的第二个部分。为什么 express 不像对任何端点调用那样将第二个调用解释为独立调用?我应该怎么做才能避免这个错误?

回答如下:

更多推荐

快速路由内的 WebSocket 仅适用于第一次调用

本文发布于:2024-05-30 22:06:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770972.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:适用于   路由   快速   WebSocket

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!