2016-11-09 46 views
1

正如標題所說,我有一個REST API的一個子一個symfony3應用使:Symfony3/Nelmio CORS /提取API - 400錯誤的請求

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

將其工作的罰款。現在我想將它移植到新的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

經過一番研究,我終於找到了錯誤。由於火狐,其扔指點我到現場的錯誤:在MDN

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

文檔