vue中配置代理
方法一(配置单个代理):
在vue.config.js中添加如下配置:
module.exports={
devServer:{
proxy:"http://localhost:5000"
}
}
请求:
getSrudent(){
axios.get('http://localhost:8080/students').then(
response=>{
console.log("请求成功",response.data)
},
error=>{
console.log("请求失败",error.message)
}
)
}
1.优点:配置简单,请求资源时直接发送给前端(8080)即可
2.缺点:不能配置多个代理,不能灵活的控制请求是否走代理
3.工作方式:按如上方式配置代理时,当请求了前端不存在的资源时,该请求会转发给服务器(优先匹配前端资源)
方法二(配置多个代理):
在vue.config.js配置具体代理规则:
module.exports={
devServer:{
proxy:{
'/api1':{//匹配所有以'/api1'开头的请求路径
target:'http://localhost:5000',//代理目标的基础路径
changeOrigin:true,
pathRewrite:{'^/api1':''}
},
'/api2':{//匹配所有以'/api2'开头的请求路径
target:'http://localhost:5000',//代理目标的基础路径
changeOrigin:true,
pathRewrite:{'^/api2':''}
}
}
}
}
请求:
getStudents(){
axios.get('http://localhost:8080/api1/students').then(
response=>{
console.log("请求成功",response.data)
},
error=>{
console.log("请求失败",error.message)
}
)
},
getCars(){
axios.get('http://localhost:8080/api2/cars').then(
response=>{
console.log("请求成功",response.data)
},
error=>{
console.log("请求失败",error.message)
}
)
},
1.优点:可以匹配多个代理,且可以灵活的控制请求是否走代理
2.缺点:配置略微繁琐,且请求资源时必须加前缀
react中配置多条代理的方法:
在src目录下新建setupProxy.js文件

const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
app.use(createProxyMiddleware('/g2', {
target: 'https://view.inews.qq.com',
changeOrigin: true,
}))
app.use(createProxyMiddleware('/api', { // 遇见 /api 前缀的请求 就会触发该代理配置
target: 'http://localhost:9999/',// 请求转发给谁
changeOrigin: true// 控制服务器接收到的请求头Host的值
}))
app.use(createProxyMiddleware('/news', {
target: 'https://interface.sina.cn/',
changeOrigin: true,
}))
app.use(createProxyMiddleware('/ncov', {
target: 'http://api.tianapi.com/',
changeOrigin: true,
}))
app.use(createProxyMiddleware('/pages', {
target: 'https://api.webhunt.cn/api/v1',
changeOrigin: true,
}))
}
具体请转:https://www.freesion.com/article/2055333464/
Vue-resource
1.下载vue-resource: npm i vue-resource
2.在main.js中引入并挂载:import vueResource from ‘vue-resource’
Vue.use(vueResource)
3.使用:使用方法与axios相同,不过通过this.$http发送请求
this.$http.get('http://localhost:8080/api1/students').then(
response=>{
console.log("请求成功",response.data)
},
error=>{
console.log("请求失败",error.message)
}
)
