react跨域请求数据(proxy)

两种方法

方法1,直接简单,但是只能设置一个固定的服务器地址,不能设置多个,在package.json设置一个proxy代理设置,拼接对应的网址;如:"proxy":"http://localhost:3000"即可

{
  "name": "my-appone",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.2.3",
    "http-proxy-middleware": "^2.0.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.7.0",
    "react-scripts": "5.0.1",
    "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://local;host:3000"
}

方法2,使用第三方包http-proxy-middleware

使用前npm或者yarn安装,然后再src同级文件下创建一个setupProxy.js文件夹,里面写好对应的配置

此方法可以设置多个不同域名的服务器请求数据

这个方法是自动循环配对对应的api前缀

const { createProxyMiddleware } = require('http-proxy-middleware') //引入

module.exports = app =>{
    app.use('/api',proxy.createProxyMiddleware({
        target:"https://elm.cangdu.org", //只要再文档中遇见/api前缀的请求,就会触发该代理配置
        changeOrigin:true,//默认false,是否需要改变原始主机头为目标URL
        // ws: true,                         // 是否代理websockets
        // pathRewrite: {
        //     '^/api/old-path' : '/api/new-path',     // 重写请求,比如我们源访问的是api/old-path,那么请求会被解析为/api/new-path
        //     '^/api/remove/path' : '/path'           // 同上
        // },
        // router: {
        //     // 如果请求主机 == 'dev.localhost:3000',
        //     // 重写目标服务器 'http://www.example.org' 为 'http://localhost:8000'
        //     'dev.localhost:3000' : 'http://localhost:8000'
        // }
    },
       proxy.createProxyMiddleware('/api2',{
            target:'http://localhost:5001',
            changeOrigin:true,
            pathRewrite:{'^/api2':''}
        }),
  ))
}

猜你喜欢

转载自blog.csdn.net/m0_64207574/article/details/128756328