正如标题所说,我有一个symfony3应用程序,在子域上有一个rest api,以便:
GET http://ajax.localhost.dev:10190/menus
返回JSON格式的菜单列表。
这是nelmio cors bundle (/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;
}
};
运行正常。现在我正试图将其移植到新的获取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,它就可以工作了。
我猜有一些认证问题,但只是不知道如何解决它。我该怎么做呢?
经过一番研究,我终于发现了这个错误。多亏了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 });
Docs on MDN