【问题标题】:Symfony3 / Nelmio cors / fetch api — 400 Bad RequestSymfony3 / Nelmio cors / fetch api — 400 错误请求
【发布时间】:2017-03-23 03:06:54
【问题描述】:

正如标题所说,我有一个 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 Request,带有Request Method: OPTIONS。如果我只是在浏览器中输入 url,它就可以工作。

我猜有一些身份验证问题,但不知道如何解决它。我该怎么做?

【问题讨论】:

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


    【解决方案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 上的文档

    【讨论】:

      猜你喜欢
      • 2015-11-28
      • 2019-09-15
      • 2022-01-04
      • 2018-07-08
      • 2020-11-13
      • 2011-06-18
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多