【问题标题】:Why am I still getting a CORS Error after enabling CORS为什么启用 CORS 后仍然出现 CORS 错误
【发布时间】:2020-06-22 23:05:52
【问题描述】:

这是获取请求:

class App extends Component {
    componentDidMount() {
        fetch('http://localhost:3001/')
            .then((res) => res.json())
            .then((data) => console.log(data));
    }

    render() {
        return <div></div>;
    }
};

这是后端代码:

const express = require('express');
const app = express();
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', '*');
    next();
});
app.use('/', (req, res) => {
    res.json({ test: 'test' });
});
app.listen(3001, console.log('listeing...'));

错误:

从原点获取 'http://localhost:3001/' 的访问权限 'http://localhost:3000' 已被 CORS 策略阻止:否 'Access-Control-Allow-Origin' 标头出现在请求的 资源。如果不透明的响应满足您的需求,请设置请求的 模式为“no-cors”以获取禁用 CORS 的资源。

【问题讨论】:

  • 你应该看看 CORS express 中间件expressjs.com/en/resources/middleware/cors.html
  • @Nick 我已经调查过了。但是这些示例并不能解决错误。 app.use(cors()) 也不起作用。
  • app.use(cors());我相信,对吧?
  • 是的,没错。
  • 看起来您的路线定义中可能有错字。应该是app.get('/' ... 而不是app.use(

标签: reactjs express cors fetch


【解决方案1】:

您必须允许客户端使用 http 方法:

res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE'); // allow client to use http methods

【讨论】:

  • 我已经尝试允许使用 http 方法,但这也不起作用。
【解决方案2】:

最简单的选择是安装 cors 包。

安装:

npm i cors

用法:

const cors = require('cors')
app.use(cors())

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 2021-09-21
    • 2020-05-25
    • 2021-03-01
    • 2016-03-21
    • 2020-01-01
    • 2019-11-29
    • 2019-04-29
    • 2018-12-23
    相关资源
    最近更新 更多