【问题标题】:I have a cross-domain request problem about React我有一个关于 React 的跨域请求问题
【发布时间】:2021-11-03 11:58:49
【问题描述】:

我有问题。点击按钮,页面报错。

"从源访问 'http://localhost:8000/hello' 处的 XMLHttpRequest 'http://localhost:3000' 已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。”

这是客户端代码

    function SendRequest() {
        axios({
            url: "http://localhost:8000/hello",
            method: "GET",
        }).then((res)=>
        {
            console.log(res);
        });
    }

这是服务器代码

     app.use((ctx, next) => {
        console.log("ASDFSFDSF");
        createProxyMiddleware({
            target: "http://localhost:8000",
            changeOrigin: true
        })
    });

服务端使用koa框架

【问题讨论】:

    标签: reactjs koa2 http-proxy-middleware


    【解决方案1】:

    如果你使用 express 作为后端框架,你可以安装一个 CORS 中间件(npm i cors 在你的后端目录中)并通过调用 app.use(cors()) 将其用作活动中间件(全局,因此对于每个传入的请求)使用const cors = require("cors") 导入后。

    有关 express 和 CORS 中间件的更多信息,请参阅 here

    【讨论】:

      【解决方案2】:

      这不是 React 问题。那是阻止对您的应用程序的请求的后端。阅读有关 CORS 的更多信息。

      【讨论】:

        猜你喜欢
        • 2010-10-13
        • 1970-01-01
        • 2023-04-04
        • 2013-11-09
        • 2014-08-04
        • 2023-03-12
        • 1970-01-01
        • 2016-02-24
        • 2015-02-08
        相关资源
        最近更新 更多