1.使用create-react-app的代理配置

   可以在项目根目录下的package.json文件中添加proxy字段来配置代理:

{
   ...

  "proxy": "http://localhost:5000"
}
//注意:比如当前端口是3000,先在当前端口3000中找对应路径内容,找不到就去5000中

2.使用http-proxy-middleware库

  create-react-app中内置http-proxy-middleware,只需要在src目录下新建setupProxy.js

//setupProxy.js
const proxy = require('http-proxy-middleware') //这里用require()引入,是因为这里用commonjs规范
module.exports = function (app) {
    app.use(proxy('/api', {
        target: 'http://localhost:5000',
        changeOrigin: true,
        pathRewrite: {
            '^/api': ''
        }
    }))
}

3.craco 扩展webpack配置

  安装

npm i -D @craco/craco

   package.json里面做如下改动:

"scripts": {
-  "start": "react-scripts start"
+  "start": "craco start"
-  "build": "react-scripts build"
+  "build": "craco build"
-  "test": "react-scripts test"
+  "test": "craco test"
}

根目录建文件craco.config.js

module.exports={
    //...
    // ...
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:5000',
                changeOrigin: true
            }
        }
    }
}

next.js中解决跨域问题用重定向解决:

/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/_api/:path*',
        destination: `http://localhost:5000/_api/:path*`,
      },
    ];
  }
}
module.exports = nextConfig

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐