适用于第一次调用"/>
快速路由内的 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 仅适用于第一次调用
发布评论