【发布时间】:2017-07-08 01:17:36
【问题描述】:
我在使用以下代码连接到套接字 io 和 express 服务器时遇到了很多麻烦。 我可以在浏览器中连接到网页/api,但是一旦我尝试从 index.html 连接套接字连接,我就会收到如下错误
这是我的“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>
【问题讨论】:
标签: node.js socket.io http-status-code-404