您当前的位置: 首页 > 

【03】

暂无认证

  • 6浏览

    0关注

    196博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Proxy代理配置解析

【03】 发布时间:2022-09-14 10:29:01 ,浏览量:6

create-react-app >= 2.0

create-react-app脚手架2.0版本以上只能配置string类型:

"proxy": "https://xxx.com",

寻找配置来源 在这里插入图片描述 在这里插入图片描述

这里的配置指向package.json里面的proxy属性, 在这里插入图片描述 这是一个全局配置,如果你请求了 /api/xxx,只要/api/xxx不是路由且不是资源路径,就会识别为一个外部请求,最终请求localhost:3000/api/xxx => https://xxx.com/api/xx

create-react-app < 2.0

create-react-app脚手架2.0版本以内配置是object类型:

"proxy":{
   "/api/**":{
      "target":"https://xxx.com",
      "changeOrigin": true
    }
}
create-react-app >= 2.0 推荐配置
npm i http-proxy-middleware

找到 webpackDevServer.config.js onBeforeSetupMiddleware添加中间件配置 在这里插入图片描述 找到 paths.proxySetup 在这里插入图片描述 发现配置文件是在src/setupProxy.js

新建src/setupProxy.js并添加代理配置

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

module.exports = function (app) {
  app.use(
    createProxyMiddleware("/api1", {
      target: "https://xxx.com",
      changeOrigin: true,
      pathRewrite: {
        "^/api1": "",
      },
    })
  );
  app.use(
    createProxyMiddleware("/api2", {
      target:
        "https://web03.cn",
      changeOrigin: true,
      pathRewrite: {
        "^/api2": "/api2",
      },
    })
  );
};

请求 /api1/list => https://xxx.com/list /api2/list => https://web03.cn/api2/list

为啥新建了proxy文件,但是不生效?请注意引入的配置文件地址是否相同,最根本的他就是直接在devServer里面配置

在这里插入图片描述

vue配置

vue.config.js

	devServer: {
		disableHostCheck: true,
		hot:true,//热更新
		open: true,// 启动是否自动打开浏览器
		proxy: {
			'/pioneer': {
				target: 'https://xxx.com',
				pathRewrite: {"/pioneer" : ""}, // 后台在转接的时候url中是没有 /api 的
				changeOrigin: true, // 加了这个属性,那后端收到的请求头中的host是目标地址 target
			}
			},
		}
	},
关注
打赏
1657344724
查看更多评论
立即登录/注册

微信扫码登录

0.0391s