代码之家  ›  专栏  ›  技术社区  ›  Nemanja G

带凭据和通配符*-“访问控制允许源”标题问题

  •  0
  • Nemanja G  · 技术社区  · 5 年前

    我在nodejs中有一个应用程序,它将充当连接到各种社交平台的代理。流程如下:

    1. 在关闭窗口之前,将访问令牌作为nonce添加到cookie(目前应用程序位于localhost上,因此令牌位于该域上),并将其添加到数据库。

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

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

    'http://something.test:8080' 表示为用户网站。

    有人知道解决办法吗,如果有的话?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Quentin    5 年前

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