繁体   English   中英

withCredentials 和通配符 * - 'Access-Control-Allow-Origin' 标头问题

[英]withCredentials and wildcard * - 'Access-Control-Allow-Origin' header issue

我在 nodejs 中有一个应用程序,它将作为连接到各种社交平台的代理。 流程是这样的:

  1. 点击一个按钮,打开一个新窗口
  2. 在关闭窗口之前,将访问令牌添加到 cookie(目前应用程序位于本地主机上,因此令牌位于该域上)作为随机数并将其添加到数据库中。
  3. 模式关闭后,转到另一个端点,该端点将从 cookie 中获取该随机数,在数据库中搜索并返回令牌。

这是问题所在,在为第 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));
}

这是错误:

从来源“ http://something.test:8080 ”访问位于“ http://localhost:9057/facebook/gettoken ”的 XMLHttpRequest 已被 CORS 策略阻止:“Access-Control-Allow-Origin”的值当请求的凭据模式为“include”时,响应中的标头不能是通配符“*”。 XMLHttpRequest 发起的请求的凭据模式由 withCredentials 属性控制。

我无法将'http://something.test:8080'代表的域列入白名单,因为它们将是用户网站。

任何人都知道解决方法,如果有的话?

请参阅文档

他们给出了如何使用动态原点的示例:

 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)
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM