我无法弄清楚为什么我会收到404错误。我已经浏览了本网站上涵盖' express-ws'的所有其他问题。并且我已经准确地为我的代码建模了解决方案规定但websocket还没有建立联系。我试图在我的快速服务器和反应应用程序之间创建一个websocket连接。以下是我的代码的预览:
使用express-ws(server.js)快递:
var express = require('express');
var expressWs = require('express-ws');
var bodyParser = require('body-parser');
var cors = require('cors');
var nodemailer = require('nodemailer');
var email = require('./credentials');
var port = process.env.PORT || 3001;
var path = require('path');
// const WebSocket = require('ws');
// const http = require('http');
expressWs = expressWs(express());
let app = expressWs.app;
var server = require('http').createServer(app);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
if (process.env.NODE_ENV === 'production') {
app.use(express.static('app/build'));
}
app.get('/', function(req, res){
console.log('server running!');
res.end();
});
app.ws('/ws', function(ws, req) {
console.log( 'socket running!' );
});
server.listen(port);
console.log('server started on port ' + port);
GET路线工作正常但是ws路线没有。
致电React app来表达:
componentDidMount() {
let ws = new WebSocket('ws://localhost:3001/ws');
ws.on( 'open', function open() {
console.log('app connected to websocket!');
} );
ws.on( 'message', function ( message ) {
console.log( message );
})
}
我已经查看了以下所有问题,并且不明白为什么他们的解决方案对我不起作用:
如果有人能让我知道会发生什么事情会很棒。
答案 0 :(得分:0)
您的代码似乎没有关注express-ws
' s document。要使用express-ws
并创建WebSocket端点,代码将为:
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
...
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
console.log('socket running');
});
app.listen(3000);
在客户端,ws
对象没有字段on
。要收听WebSocket连接和消息,您可以使用onopen
和onmessage
:
ws.onopen = function() {
console.log('app connected to websocket!');
};
ws.onmessage = function(message) {
console.log( message );
};