gpt4 book ai didi

javascript - 响应中的 Access-Control-Allow-Origin header 不能是通配符 '*' ... Socket.io、NodeJs、ReactJs

转载 作者:行者123 更新时间:2023-11-30 20:13:39 25 4
gpt4 key购买 nike

我是 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 app 中的以下代码和我的 React 应用程序作为 http://localhost:3000 托管在端口 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 (Method Not Allowed) Failed to load http://127.0.0.1:8848/socket.io/?EIO=3&transport=polling&t=MMT-Aso: 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 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

谁能帮我解决这个问题。

最佳答案

根据 MDN Web Doc,您可以添加主机 url。

解决方案一

可能已经回答了类似的问题。如果这对您不起作用,请尝试解决方案 2。

这是 stackoverflow 的答案:Solution 1

方案二

Limiting the possible Access-Control-Allow-Origin values to a set of allowed origins requires code on the server side to check the value of the Origin request header, compare that to a list of allowed origins, and then if the Origin value is in the list, to set the Access-Control-Allow-Origin value to the same value as the Origin value.

Access-Control-Allow-Origin: https://abc.xyz.gi

所以在你的情况下

Access-Control-Allow-Origin: https://localhost

Access-Control-Allow-Origin: https://127.0.0.1

进一步相关的质量检查 read more on stackeoverflow

关于javascript - 响应中的 Access-Control-Allow-Origin header 不能是通配符 '*' ... Socket.io、NodeJs、ReactJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52144257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com