config.js
// 请求地址
const BASE_URL = "https://localhost:8080"
const TIMEOUT = 10000
export {
BASE_URL,
TIMEOUT
}
server.js
假设这里返回的数据结构为
{
"code": 0,
"msg": "提示信息",
"data": "返回数据"
}
当code == 401时重新登录
import { BASE_URL, TIMEOUT } from './config'
/**
* 请求封装
* @param body
* @returns {Promise<unknown>}
*/
export function request(body){
let url = body.url;
let data = body.data;
let method = body.method;
let header = body.header ? body.header : {};
wx.showLoading({
title: "加载中",
mask: true //开启蒙版遮罩
});
header['Authorization'] = 'Bearer ' + wx.getStorageSync('token')
//返回Promise对象
return new Promise((resolve, reject)=> {
wx.request({
url: BASE_URL + url,
timeout: TIMEOUT,
method: method,
data: data,
header: header,
success: (res) => {
if (res.data && res.data.code == 401) {
// 跳转登录
reject(res.data);
wx.navigateTo({
url: '/pages/login/login',
})
}
resolve(res.data);
},
fail: (res) => {
wx.showToast({
title: res.data.msg ? res.data.msg : '请求数据失败,请稍后重试',
icon: 'error',
duration: 2000
})
reject(res);
},
complete: () => {
wx.hideLoading();
}
})
})
}
如何使用:
新建api目录存放接口
get方法:
import request from "../server";
/**
* 查询网点列表
* @param {} params
* @returns
*/
export function getPlaceList(params) {
return request({
'url': '/wechat/place/list',
'method': 'get',
'params': params
})
}
post方法,application/json
export function orderCrate(params) {
return request({
'url': '/wechat/order/orderCreate',
'method': 'post',
'data': params
})
}
post方法,application/x-www-form-urlencoded
export function rechargeMoney(data) {
return request({
'url': '/wechat/pay/recharge/money',
'method': 'post',
'data': data,
'header': {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
}
在page的js文件中使用
在最外层引入api下面的js
import {getCatDetail} from '../../api/modules/car'
方法使用
getCatDetail({carId: options.id}).then(res => {
if (res.code == 200) {
let data = res.data
}
})
标签:url,微信,request,res,data,method,wx
From: https://www.cnblogs.com/LiuFqiang/p/18418067