1.根目录下创建 vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:7788',
ws: true,
changeOrigin: true,
pathRewirte:{ //路径重写
'^/api':''
}
},
'/foo':{
target:'http://localhost:3001'
}
}
}
}
2.修改发送请求:
在page/index.vue中
// 获取首页数据
methods: {
//2.请求首页数据
async getIndexData() {
// #ifdef MP-WEIXIN
let {data:res} = await http('/getIndexData'); //小程序
// #endif
// #ifdef H5
let {data:res} = await http('/api/getIndexData'); //h5
// #endif
console.log(res);
}
},
3.untils/request.js 中写条件判断
import config from './config.js';
export default (url, data = {}, method = 'GET') => {
return new Promise((resolve, reject) => {
uni.request({
// #ifdef MP-WEIXIN
url: config.baseUrl + url, //小程序
// #endif
// #ifdef H5
url,
//#endif
data,
method,
success: (res) => {
resolve(res)
},
fail: (erro) => {
reject(erro)
}
})
})
}
4.如果在h5中还是不行
"h5": {
"title": "Test",
"devServer": {
"port": 8082,
"disableHostCheck": true,
"proxy": {
"/api": {
"target": "http://localhost:7788",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/api": ""
}
}
}
}
}