无心Code

Come on baby!

   ::  :: 新随笔  ::  ::  :: 管理

前端请求代理配置,解决跨域问题,适用于React、Vue项目

  1. 优点:可以配置多个代理,可以灵活控制请求是否走代理。
  2. 缺点:配置繁琐,前端请求资源时必须带上前缀。

第一步 安装

yarn add http-proxy-middleware --save

第二步 新建文件

在项目的 src 目录下新建文件 setupProxy.js ,脚手架会自动解析该文件。

第三步 配置代理

在setupProxy.js文件中写入如下代码配置:

const { createProxyMiddleware } = require ('http-proxy-middleware');
module.exports = function(app){
  app.use(
    createProxyMiddleware(
      '/api1',                        //使用 /api 前缀代理配置,(代理1前缀)
      target:'http://localhost:3000', //需要跨域的服务器地址
      //changeOrigin:true 。 控制服务器接收到奥的请求头中host字段的值,值为 localhost:5000
      //changeOrigin:false  控制服务器接收到奥的请求头中host字段的值,值为 localhost:3000
      //此处的值默认为false,我们要设置为:true,如下:
      changeOrigin:true,
      pathRewrite:{
        '^/api1':''
      }              
    ),

    createProxyMiddleware(
      '/api2',                        //使用 /api 前缀代理配置,(代理2前缀)
      target:'http://localhost:3000', //需要跨域的服务器地址
      //changeOrigin:true 。 控制服务器接收到奥的请求头中host字段的值,值为 localhost:5000
      //changeOrigin:false  控制服务器接收到奥的请求头中host字段的值,值为 localhost:3000
      //此处的值默认为false,我们要设置为:true,如下:
      changeOrigin:true,
      pathRewrite:{
        '^/api2':''
      }              
    )
  )
}

第四步 安装 axios 请求库

yarn add axios --save

第五步 开始 axios 请求

import axios form "axios";
//GET请求 比如接口是:"/getData" ,则下面必须要带上 /api1 前缀
axios.get("/api1/getData", {params:{a:10,b:'ok'}}).then(res=>{
  console.log(res)
})


//POST请求 比如接口是:"/getData" ,则下面必须要带上 /api1 前缀
const result = axios.get("/api2/getData", {a:10,b:'ok'}).then(res=>{
  console.log(res)
})

posted on 2023-10-12 10:35  melong  阅读(545)  评论(0)    收藏  举报