正如标题所说,我有一个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
。如果我只是在浏览器中输入网址,那就可以了。
我猜有一些身份验证问题,但是无法弄清楚如何解决它。我怎么能这样做?
答案 0 :(得分:1)
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 });
上的文档