![](https://i-blog.csdnimg.cn/direct/0cb403274c234f588610263a72b894c0.png)
![](https://i-blog.csdnimg.cn/direct/4424a74367aa41479ab2fd9f526de241.png)
1. 项目根目录新建vue.config.js 内容如下
![](https://i-blog.csdnimg.cn/direct/623785473e324ce58a32474704ddf113.png)
let { HTTP_REQUEST_URL } = require("./config/httpUrl");
module.exports = {
devServer: {
disableHostCheck: true,
proxy: {
"/api": {
target: "填写你的地址",//http://192.168.1.111:81/api
changeOrigin: true,
secure: false,
ws: false,
pathRewrite: {
"^/api": "",
},
},
},
},
};
2. request.js文件修改,做h5与app的兼容处理
![](https://i-blog.csdnimg.cn/direct/538566a0c1cc48ae8ffd7cdeaeb0df6d.png)
let { HTTP_REQUEST_URL, TIME_OUT } = require("@/config/httpUrl.js");
import store from "../store/index.js";
import db from "./localstorage.js";
let request = {
get: (url, data) => {
return new Promise((resolve, reject) => {
uni.request({
// h5 请求路径不能写全路径 不然即使配置了跨域,浏览器还是会显示跨域
// #ifdef H5
url: "/api" + url,
// #endif
// #ifndef H5
url: HTTP_REQUEST_URL + url, // 非H5端即微信小程序或App
// #endif
data,
method: "GET",
timeout: TIME_OUT,
header: {
"content-type": "application/json", // 默认值
Authorization: db.get("TOKEN"),
},
success: (res) => {
if (res.data.code == 200) {
resolve(res.data);
} else {
reject(res.data);
errorMsg(res.data);
}
},
fail: (error) => {
reject(error);
if (error.errMsg === "request:fail timeout") {
wx.showToast({
title: "请求超时",
icon: "error",
duration: 3500,
});
return;
}
},
});
});
},
post: (url, data) => {
return new Promise((resolve, reject) => {
uni.request({
// h5 请求路径不能写全路径 不然即使配置了跨域,浏览器还是会显示跨域
// #ifdef H5
url: "/api" + url,
// #endif
// #ifndef H5
url: HTTP_REQUEST_URL + url, // 非H5端即微信小程序或App
// #endif
data,
method: "POST",
timeout: TIME_OUT,
header: {
"content-type": "application/json", // 默认值
Authorization: store.state.token,
},
success: (res) => {
if (res.data.code == 200) {
resolve(res.data);
} else {
reject(res.data);
errorMsg(res.data);
}
},
fail: (error) => {
reject(error);
if (error.errMsg === "request:fail timeout") {
wx.showToast({
title: "请求超时",
icon: "error",
duration: 3500,
});
return;
}
},
});
});
},
};
// 错误提示
function errorMsg(_data) {
let date = 2000;
if (_data.msg == "未注册") {
return wx.reLaunch({
url: "/pages/login/login/login",
});
}
if (_data.msg == "不存在当前用户,请注册") {
uni.showToast({
title: _data.msg,
icon: "none",
duration: date,
});
return uni.reLaunch({
url: "/pages/login/login/login",
});
}
if (_data.msg == "认证失效,请重新登录") {
uni.showToast({
title: _data.msg,
icon: "none",
duration: date,
});
setTimeout(() => {
return uni.reLaunch({
url: "/pages/login/login/login",
});
}, 1000);
}
return uni.showToast({
title: _data.msg || "请稍后重试",
icon: "none",
duration: date,
});
}
export default request;