Symfony3 / Nelmio cors / fetch api - 400 Bad Request

时间:2016-11-09 10:25:30

标签: symfony ecmascript-6 cors fetch-api nelmiocorsbundle

正如标题所说,我有一个symfony3应用程序,在子域上有一个rest api,所以:

GET http://ajax.localhost.dev:10190/menus

以JSON格式返回菜单列表。

这是nelmio cors包(/app/config/nelmio/cors.yml

的配置
nelmio_cors:
  paths:
    '^/':
      origin_regex: true
      allow_origin: ['^https?://%domain%:[0-9]+']
      allow_headers: ['X-Custom-Auth']
      allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
      max_age: 3600
      hosts: ['^ajax\.']
      allow_credentials: true

我一直在使用这段代码:

export default class AppRemote extends Remote {
  get host () { return `ajax.${super.host}`; }
  open(xhr, data) {
    if ("withCredentials" in xhr) { 
      xhr.open(data.method, this.url(data.url), true);
      xhr.withCredentials = true; }

    else if (typeof XDomainRequest != "undefined") {
      xhr = new XDomainRequest();
      xhr.open(data.method, this.url(data.url)); }

    else { this.app.error('cannot init CORS Request'); }

    return xhr;
  }
};

工作正常。现在我尝试将其移植到新的fetch API,我正在使用此代码:

const init = (url, method = 'GET') => {
  return new Request(url, {
    headers: new Headers({
      'Access-Control-Allow-Credentials': true,
      //'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS'
    }),
    mode: 'cors',
    credentials: true,
    method });
}

const get = (url) => {
  return fetch(init(url));
}

返回400 Bad RequestRequest Method: OPTIONS。如果我只是在浏览器中输入网址,那就可以了。

我猜有一些身份验证问题,但是无法弄清楚如何解决它。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

经过一番研究,我终于找到了错误。感谢Firefox,它将错误指向了我的位置:

return new Request(url, {
  //headers: new Headers({
    //'Access-Control-Allow-Credentials': true,
    //'Access-Control-Allow-Origin': '*',
    //'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS'
  //}), //<-- working without headers at all
  mode: 'cors',
  credentials: 'include', //<-- that is the right setting
  method });

MDN

上的文档