【发布时间】:2019-02-08 04:28:39
【问题描述】:
我是 socket.io 的新手。我的 NodeJs/Express 服务器中有以下代码
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
io.on('connection', socket => {
console.log('New client connected');
socket.on('disconnect', () => console.log('Client disconnected'));
socket.emit('FromAPI', 'hello');
});
//My port here is 8848
app.listen(app.get('port'), () => {
logger.log('info', `Server started at :${app.get('port')}`);
});
Client React 应用程序中的以下代码和我的反应应用程序托管在端口 3000 中,为 http://localhost:3000
import socketIO from 'socket.io-client';
componentDidMount() {
const endPoint = 'http://127.0.0.1:8848';
const socket = socketIO(endPoint);
socket.on('FromAPI', data => console.log(data));
}
使用此代码,我在浏览器控制台上收到以下错误:
polling-xhr.js:263 GET http://127.0.0.1:8848/socket.io/?EIO=3&transport=polling&t=MMT-4kl 405(不允许的方法) 无法加载http://127.0.0.1:8848/socket.io/?EIO=3&transport=polling&t=MMT-Aso:当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。因此,Origin 'http://localhost:3000' 不允许访问。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。
请任何人帮我解决这个问题。
【问题讨论】:
-
您的浏览器中是否有 CORS 扩展。如果是,请打开它。如果不使用这个 chrome 扩展并尝试。 [chrome.google.com/webstore/detail/moesif-origin-cors-change/…
-
您需要使用正确的(调用)主机作为
access-control-allow-origin的值进行响应 - 但老实说,我无法看到您的 CORS 标头是从哪里发送的 -
@anjuc - 这是非常糟糕和危险的建议
标签: javascript node.js reactjs socket.io