gpt4 book ai didi

angularjs - CORS Node js问题

转载 作者:搜寻专家 更新时间:2023-10-31 22:23:16 25 4
gpt4 key购买 nike

浏览了堆栈上的多个帖子后,我仍然找不到正确的答案。

检查了 CORS 上的文档扩展也是如此。

我启动并运行了以下服务器代码:

var WebSocketServer = require("ws").Server
var http = require("http")
var express = require('express')
var cors = require('cors')
var app = express();

app.use(cors());
var port = process.env.PORT || 9000

var server = http.createServer(app)
server.listen(port)
var count = 0;
var clients = {};
var rooms = {};
var wss = new WebSocketServer({server: server})
wss.on("connection", function(ws) {
ws.on("create-room", function(data) {
rooms[data] = {creator : data.user_id, created : new Date()}
})
ws.on("close", function() {
console.log("websocket connection close")
})
})

但是我得到:

XMLHttpRequest cannot load http://localhost:9000/socket.io/?EIO=3&transport=polling&t=LE-CbU0. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:8100' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

如果我用 app.use(cors());

注释行

我明白了:

XMLHttpRequest cannot load http://localhost:9000/socket.io/?EIO=3&transport=polling&t=LE-Cwb8. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 404.

很明显我的服务器已经启动并运行正常但是

最佳答案

如错误消息所述,通配符 Access-Control-Allow-Origin 来源不能与 Access-Control-Allow-Credentials 一起使用。默认情况下,cors 模块使用原始来源,并且默认情况下 socket.io 需要凭据(至少在这里看起来是这样)。您需要做的是读取请求的 Origin header ,并将其包含在响应的 Access-Control-Allow-Origin 中。

幸运的是,cors 使这变得非常简单:为了反射(reflect)请求来源,传入一个具有 origin: true 属性的选项对象。您还需要一个 credentials: true 属性以完全允许凭据:

app.use(cors({
origin: true,
credentials: true
}));

关于angularjs - CORS Node js问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36267171/

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