gpt4 book ai didi

node.js - express -ws : "ws.send is not a function"

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:10 38 4
gpt4 key购买 nike

我正在使用 Node.js + Express + Express-ws 创建应用程序,但在连接后尝试发送消息时出现以下错误:

const fs        = require('fs');
const http = require('http');
const https = require('https');
const express = require('express');
const app = express();

/*
const key = fs.readFileSync('./security/server-key.pem', 'utf8');
const cert = fs.readFileSync('./security/server-crt.pem', 'utf8');
const ca = fs.readFileSync('./security/ca-crt.pem', 'utf8');
const credentials = {key: key, cert: cert, ca: ca};
var httpsServer = https.createServer(credentials, app);
*/

var httpServer = http.createServer(app);

httpServer.listen(8443, function(){
console.log('Listening on *:8443 \n');
});

httpServer.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: ' + message);
ws.send(message);
});
ws.send('Hi there, I am a WebSocket server');
});

//ROUTES
app.get('/charger/:id', function(req, res){
res.send('<h1>Hello ' + req.params.id + '</h1>');
});

app.get('*', function(req, res){
res.status(404).send('404 — Not Found');
});

注释部分是为了验证我以后可以使用 HTPPS 而无需更改太多内容。

错误如下:

TypeError: ws.send is not a function
at Server.<anonymous> (index.js:26:5)
at Server.emit (events.js:194:15)
at TCP.onconnection (net.js:1517:8)

最佳答案

据我所知,这是因为您实际上并没有在任何地方使用 express-ws 包。此外,httpServer 对象是 http.Server 的一个实例类,并且没有内置的 websockets 知识。即使您在回调 ws 中调用参数,它实际上并不是一个 websocket 对象——它是 http.ClientRequest 的一个实例。类,它没有 send 方法,因此 ws.send is not a function 错误。因此,要解决此问题,我认为您需要根据 the docs 按照这些思路做一些事情。 :

const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);

app.ws('/', function(ws, req) {
// Now you have a ws object available
})

希望对您有所帮助,祝您好运!

关于node.js - express -ws : "ws.send is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54792014/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com