Vue项目devServer.proxy代理配置详解

  • 目录
    • 概述
      • 需求:
    • 设计思路
    • 实现思路分析
      • 1..config.js文件中,引入依赖项
      • 2.devServer.proxy 可以是一个指向开发环境 API 服务器的字符串
      • 3.更多控制行为
  • 参考资料和推荐阅读

Survive by day and develop by night.
talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for change,challenge Survive.
happy for hardess to solve denpendies.

目录

Vue项目devServer.proxy代理配置详解

概述

Vue项目devServer.proxy代理配置详解的是一个非常常见的需求。

需求:

设计思路

如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。可以通过 *.config.js 中的 devServer.proxy 选项来配置。

实现思路分析

1…config.js文件中,引入依赖项

这里我们可以使用规则的数据结构来存储和转发。

2.devServer.proxy 可以是一个指向开发环境 API 服务器的字符串

//服务器会将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:4000上
module.exports = {
devServer: {
proxy: ‘http://localhost:4000’
}
}

3.更多控制行为

const proxy = require(‘http-proxy-middleware’);

module.exports = {
devServer:{
host: ‘localhost’,//target host
port: 8080,
//proxy:{‘/api’:{}},代理器中设置/api,项目中请求路径为/api的替换为target
proxy:{
‘/api’:{
target: ‘http://192.168.1.30:8085’,//代理地址,这里设置的地址会代替axios中设置的baseURL
changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
//ws: true, // proxy websockets
//pathRewrite方法重写url
pathRewrite: {
‘^/api’: ‘/’
//pathRewrite: {‘^/api’: ‘/’} 重写之后url为 http://192.168.1.16:8085/xxxx
//pathRewrite: {‘^/api’: ‘/api’} 重写之后url为 http://192.168.1.16:8085/api/xxxx
}
}}
},
//…
}
proxy: {
‘/bff/favoritesInfo’: {
// target: ‘http://192.168.85.85:5110/’,
target: ‘http://localhost:8080//’,
ws: false,
changeOrigin: true,
pathRewrite: { // 后端MOCK开关
‘^/bff/favoritesInfo’: ‘jsti-pm-bff-pc/bff/favoritesInfo’
}
},
sc: {
// target: ‘http://127.0.0.1:8082/’, // 请求本地 需要boot后台项目

  ws: false,
    changeOrigin: true
  }

参考资料和推荐阅读

[1]. https://www.jianshu.com/p/8493282fe232

欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!~

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。