react 多个 后台地址 跨域配置

虽然 可以  用 axios 写 完整 的 baseurl ,然后 请求 服务器地址  但是 在用 fastapi 的时候 发现 跨域还是 有坑 ,尽量 避免 跨域

可以 使用  react 的 proxy 功能  ,这样不会报跨域 问题 

1. yarn add http-proxy-middleware 

2.在src 目录下 创建 setupProxy.js 

3. 

const {createProxyMiddleware} = require("http-proxy-middleware");

module.exports = function (app) {
    app.use(
        createProxyMiddleware(
            '/api',  // 请求 是 /api开头的 就 访问  底下的ip 
            {
                target: 'http://10.168.1.2:8000',
                changeOrigin: true
            }
        )
    )
    app.use(
        createProxyMiddleware(
            '/versions', //请求是 /versions 开头 的就 访问 底下的ip 
            {
                target: 'http://10.168.1.6:20150',
                changeOrigin: true
            }
        )
    )
};

 

记得axios 请求的时候 应该是 axios.get("api/duud" ) 这样的 格式 ,不 能是 http://localhost:9999/api/dudu 这样的, 不然还是会报跨域

posted @ 2021-12-10 17:01  ifnk  阅读(632)  评论(0编辑  收藏  举报