我正在使用NodeJS,EJS作为模板引擎和Socket.io构建聊天应用程序。当我在布局视图中初始化Socket.io实例时,它会出现以下错误:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=Lzz8iVx 400 (Bad Request)
这是我在服务器上的代码:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var layouts = require('express-ejs-layouts');
// other dependencies
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(layouts);
// Here goes the server
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.set('transports', ['websocket']);
io.on('connection', function (socket) {
console.log('A client connected!');
});
server.listen(3000, function () {
console.log('Listening on 3000');
});
这是我的 layout.ejs :
<html>
<head>
<title>Node Chat</title>
<link rel='stylesheet' href='stylesheets/bootstrap.min.css'>
<link rel='stylesheet' href='/stylesheets/main.css' />
<link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet" type="text/css">
<script src='https://code.jquery.com/jquery.js'></script>
<script src='javascripts/bootstrap.min.js'></script>
</head>
<body>
<%- body %>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
虽然我根据Socket,io docs做了所有事情,但它会导致上述错误。我也尝试了几种变体,例如更改为var io = require('socket.io').listen(server)
,但它也不起作用。我还在我的应用程序中添加了cors
库,但它也不起作用。这可能是什么问题?