无法从Heroku应用获取数据。 CORS错误

时间:2018-06-25 18:21:31

标签: express heroku redux cors fetch

我一直在努力从Redux中的heroku应用程序获取数据,并且遇到了一些CORS错误:

Failed to load https://app-name.herokuapp.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:3000' 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.

第二个错误

localhost/:1 Uncaught (in promise) TypeError: Failed to fetch

我从Express创建了Heroku应用,在响应代码中,我已经拥有

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);

我在Redux中的抓取功能看起来像

const url = "https://app-name.herokuapp.com/users";
return fetch(url, {
 method: 'GET',
 mode: 'cors',
 headers: { 'Content-Type': 'text' }
})

1 个答案:

答案 0 :(得分:1)

在您的cors设置中,您拥有http://localhost:3000,但服务器正在https://app-name.herokuapp.com上运行。