【发布时间】:2019-01-04 19:21:35
【问题描述】:
我很难让 CORS 正常工作。我正在尝试从我设置的 Heroku 应用程序中获取数据。我从 Redux 获取,并使用 ExpressJS 作为后端。我一直在查看 CORS 文档,但仍然无法弄清楚。 enter link description here
这就是它在 Express 中的样子
var express = require('express');
var router = express.Router();
var cors = require('cors')
router.options('/', cors())
router.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['*']);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
router.get('/', cors(), function(req, res, next) {
res.json({...})
}
我在我的应用程序中设置了代理到 http://localhost:3001/,但我的应用程序在 3000 上运行。我将其包括在内以防它可能是问题,但我不知道它是。
我的 Redux 文件是这样设置的
return dispatch => {
const url = "https://app-name.herokuapp.com/users";
return fetch(url, {
method: 'GET',
mode: 'cors',
headers: { 'Content-Type': 'text' }
})
完整的错误是:“无法加载https://app-name.herokuapp.com/users:对预检请求的响应未通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'标头。来源'@987654324 @' 因此不允许访问。”
【问题讨论】:
标签: express heroku redux cors fetch