2017-03-05 86 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如果您愿意。

尽管在您的生产服务器上,您可能不需要此标头,除非您有很好的跨源请求原因。