react项目中解决跨域问题

2,950 阅读1分钟

方法一: package.json文件

{
  "name": "react-staging",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "nanoid": "^3.3.4",
    "prop-types": "^15.8.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:5000"   //添加需要代理的服务。缺点:只能设置一个
}

服务器端接口请求按原来的

image.png

方法二:在src目录下新建一个js 文件setupProxy.js文件 优点:使用该方法的话就可以设置多个代理服务器

const proxy = require('http-proxy-middleware')
const proxy = require('http-proxy-middleware')
module.exports = function(app){
    app.use(
        proxy('/api1',{
            target:'http://localhost:5000',
            changeOrigin:true,
            pathRewrite:{'/api1':''}
        }),
        proxy('/api2',{
            target:'http://localhost:5001',
            changeOrigin:true,
            pathRewrite:{'/api2':''}
        })
    )
}

服务器端接口请求

         axios.get('http://localhost:3000/api1/students').then(res =>{
            console.log(res.data);
        }).catch(err =>{console.log(err);})