我有一个正在运行的 socket.io 服务器,但我无法通过 Mac 上的本地 html 文件连接到它。
错误:
Failed to load http://file/socket.io/?EIO=3&transport=polling&t=M6tFqlm: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'null' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
服务器:
var app = require('express')();
var server = app.listen(8080);
var cors = require('cors');
app.options('*', cors());
var io = require('socket.io').listen(server);
....
// think this is redudant
server.listen(8080);
本地 HTML 文件(没有本地服务器运行它)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
</head>
<body>
<script src="../socket.io-client/dist/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
// var socket = new io.Socket();
var socket = io();
//var socket = io('https://example.com:8080', { transport : ['websocket'] });
socket.connect('https://example.com:8080');
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};
</script>
<div id="date"></div>
<textarea id="text"></textarea>
</body>
</html>
最佳答案
根据MDN您将 Access-Control-Allow-Credentials header 设置为 include,这需要服务器指定该域可以访问 cookie 等。 - 这是有道理的 - 您不需要想要将 Cookie 或凭据发送到任何站点。
如果您只有一个未在任何地方托管的 HTML 文件,您所能做的就是禁用凭据,这样它们就不会被发送。我看过the internet我认为你可以将其设置为:
var socket = io({
extraHeaders: {
'Access-Control-Allow-Credentials': 'omit'
}
});
或者,您可以在浏览器中禁用 CORS,但当然,这是最后的手段,这会让您面临安全问题。
关于javascript - 当请求的凭据模式为 '*' 时,响应中的 Access-Control-Allow-Origin' header 不得为通配符 'include',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48899893/