| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- /**
- * 文档地址:https://uiadmin.net/uview-plus/js/http.html
- */
- const baseUrl = "https://bpi.shuhi.com";
- export function initRequest() {
- console.log("初始化了 http 请求代码");
- // 初始化请求配置
- uni.$u.http.setConfig((config) => {
- /* config 为默认全局配置*/
- // config.baseURL = `http://192.168.1.2:8080`; /* 根域名 */
- config.baseURL = baseUrl; /* 根域名 */
- config.custom.toast = true; // 默认消息有msg会显示出来
- config.sslVerify = false; // 忽略 SSL 证书验证
- return config;
- });
- // 请求拦截
- uni.$u.http.interceptors.request.use(
- (config) => {
- // 可使用async await 做异步操作
- // console.log('请求拦截', config)
- // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
- config.data = config.data || {};
- // 挂载 token
- let token = uni.getStorageSync("token");
- config.header.Authorization = token ? `Bearer ${token}` : "";
- return config;
- },
- (config) => {
- // 可使用async await 做异步操作
- return Promise.reject(config);
- }
- );
- // 响应拦截
- uni.$u.http.interceptors.response.use(
- (response) => {
- /* 对响应成功做点什么 可使用async await 做异步操作*/
- // console.log('响应拦截', response)
- const data = response.data;
- // 自定义参数
- const custom = response.config?.custom;
- if (data.code !== 200) {
- // 身份认证失败,需要重新登录
- if (data.code === 401) {
- uni.$u.toast(data.msg || "身份认证失败,请先登录");
- uni.removeStorageSync("token");
- setTimeout(() => {
- uni.$u.route({
- type: "reLaunch",
- url: "/pages/login/login", // 跳转到登录页
- });
- }, 1000);
- } else {
- // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
- if (custom.toast !== false) {
- uni.$u.toast(data.msg);
- }
- // 如果需要catch返回,则进行reject
- // if (custom?.catch) {
- // return Promise.reject(data)
- // } else {
- // // 否则返回一个pending中的promise,请求不会进入catch中
- // return new Promise(() => { })
- // }
- return data;
- }
- }
- // return data.data === undefined ? {} : data.data
- return data; // 这里视不同的后端返回数据格式而定
- },
- (response) => {
- // 对响应错误做点什么 (statusCode !== 200)
- return Promise.reject(response);
- }
- );
- }
- export default baseUrl;
|