-1
我在使用以下代码连接到套接字io和express服务器时遇到了很多问题。 我可以连接到浏览器的网页/ api,但只要我尝试从index.html连接套接字连接,我得到的错误如下尝试连接到套接字io/express服务器时出现404错误
这是我的'server.js'
var WebSocketServer = require('uws').Server,
express = require('express'),
path = require('path'),
app = express(),
server = require('http').createServer(),
createEngine = require('node-twig').createEngine;
app.engine('.twig', createEngine({
root: __dirname + '/public',
}));
app.set('views', './public');
app.set('view engine', 'twig');
var cors = require('cors');
app.use(cors());
app.use(require('./routes'));
app.use(require('./api'));
app.use(express.static(path.join(__dirname, '/public')));
app.use("/admin", express.static(__dirname + '/public'));
app.use("/admin/scss", express.static(__dirname + '/scss'));
app.use("/admin/vendors", express.static(__dirname + '/vendors'));
app.use("/admin/js", express.static(__dirname + '/js'));
app.use("/admin/build", express.static(__dirname + '/build'));
app.use("/scss", express.static(__dirname + '/scss'));
app.use("/vendors", express.static(__dirname + '/vendors'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/build", express.static(__dirname + '/build'));
var wss = new WebSocketServer({server: server});
wss.on('connection', function (ws) {
ws.on('join', function() {
console.log('SOMEONE JUST JOINED');
});
ws.on('close', function() {
console.log('stopping client interval');
clearInterval(id);
});
});
server.on('request', app);
server.listen(8080, function() {
console.log('Listening on http://localhost:8080');
});
,这是我的index.html文件:
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script type="text/javascript">
var so = io.connect('http://192.168.***.***:8080/');
so.on('connect',() => {
so.emit('join');
});
</scrip>
这是我不断收到错误:
XMLHttpRequest cannot load http://localhost:8080/socket.io/?EIO=3&transport=polling&t=LfHXP1O. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://192.168.4.149:8080' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
,有时我得到这个错误:
Failed to load resource: the server responded with a status of 404 (Not Found)
解决方案:
<script>
var host = window.document.location.host.replace(/:.*/, '');
var server = new WebSocket('ws://' + host + ':8080');
server.onmessage = function (event) {
updateStats(JSON.parse(event.data));
};
server.onopen = function (event) {};
</script>
你好。感谢您的回复。 1.我通过var wss = new WebSocketServer({server:server});是后端socket.io的一个实现,但只是进行了优化。 2.说我想保持服务器的状态,那我究竟能够从客户端连接到它? 对于所有的移植和websockets等我都很新 – TheMan68