2017-03-05 82 views
5

在我React的應用程序,我試圖讓從我的Heroku服務器GET請求來獲取用戶的列表:使用下面的請求提取API無法加載,CORS

https://blablabla.heroku.com/users 

const sendSearch = fetch('/https://blablabla.heroku.com/users', {credentials: 'same-origin'}) 

function loadMyUsers(data) { 
    data.json().then((jsonData) => { 
    // console.log(jsonData) 

    }) 
} 

sendSearch.then(loadMyUsers)} 

不過,我得到以下錯誤:

Fetch API cannot load https://blablabla.heroku.com/users. 
Response to preflight request doesn't pass access control check: No 
'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://localhost:8080' is therefore not allowed 
access. If an opaque response serves your needs, set the request's mode 
to 'no-cors' to fetch the resource with CORS disabled. 

我試圖改變我的獲取方法到很多東西類似:

const sendSearch = fetch('https://blablabla.heroku.com/users',{ 
    method: 'GET', 
    headers: { 
    'Accept': 'application/json', 
    'Content-Type': 'application/json', 
    'mode': 'no-cors' 
    } 
}) 

但問題依然存在。

如何製作跨域請求?

+6

您必須在後端設置正確的'Access-Control-Allow-Origin'標頭。提取請求似乎工作。 –

回答

0

在您的heroku服務器上,您應該將Access-Control-Allow-Origin: *添加到您的響應標題或更具體的Access-Control-Allow-Origin: http://localhost:8080如果您願意。

儘管在您的生產服務器上,您可能不需要此標頭,除非您有很好的跨源請求原因。