我正在使用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)
答案 0 :(得分:2)
据我所知,这是因为您实际上并没有在任何地方使用express-ws
软件包。另外,httpServer
对象是http.Server
类的实例,并且不具有websocket的内置知识。即使您在回调ws
中调用该参数,它实际上也不是websocket对象-它是http.ClientRequest
类的实例,该类没有send
方法,因此{{1 }}错误。因此,要解决此问题,我认为您需要按照the docs遵循以下原则进行操作:
ws.send is not a function
希望有帮助,祝你好运!