我在nodejs中有一个应用程序,它将作为连接到各种社交平台的代理。流程是这样的:
- 点击按钮,打开新窗口
- 在关闭窗口之前,将访问 token 添加到 cookie(目前应用程序位于本地主机上,因此 token 位于该域上)作为随机数并将其添加到数据库中。
- 模式关闭后,转到另一个端点,该端点将从 cookie 中获取该随机数,在数据库中搜索并返回 token 。
问题是这样的,在发送第3步的AJAX请求后,出现CORS问题。这是代码:
jQuery.ajax({
url: "http://localhost:9057/facebook/gettoken",
type: 'GET',
dataType: "json",
xhrFields: {
// -->> In order to access the cookie, we have to have this set as true.
withCredentials: true
},
crossDomain: true,
success: function (res) {
console.log(res);
}
});
在我的 NodeJS 应用程序中,我将 cors 设置为:
if (config.getOption('PORT')) {
const corsOptions = {
credentials: true
};
app.use(cors(corsOptions));
// -->> I cannot have * here here, withCredentials cannot be set to true and have *, see the error below
app.options('*', cors(corsOptions));
}
这是错误:
Access to XMLHttpRequest at 'http://localhost:9057/facebook/gettoken' from origin 'http://something.test:8080' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
我无法将 'http://something.test:8080'
代表的域列入白名单,因为它们将是用户网站。
任何人都知道解决方法(如果有的话)?
最佳答案
参见the docs .
他们给出了如何使用动态源的示例:
var whitelist = ['http://example1.com', 'http://example2.com'] var corsOptions = { origin: function (origin, callback) { if (whitelist.indexOf(origin) !== -1) { callback(null, true) } else { callback(new Error('Not allowed by CORS')) } } }
如果不能加入白名单,那就去掉白名单的测试吧!
var corsOptions = {
origin: function (origin, callback) {
callback(null, true)
}
}
关于javascript - withCredentials 和通配符 * - 'Access-Control-Allow-Origin' header 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59843210/