创建 http.js
function request(options) {
// 请求拦截器
// ...
// 1. 加一些统一的参数,或者配置
if (!options.url.startsWith("https://") && !options.url.startsWith("http://")) {
options.url = "https://showme2.myhope365.com" + options.url
}
// 默认的请求头
let header = {
'context-type':'application/json',
'token': wx.getStorageSync('token') || ""//后端能够获取token
};
if (options.header) {
header = {
...header,
...options.header
}
}
return new Promise((reslove, reject) => {
// 调用接口
wx.request({
// 默认的配置
// 加载传入的配置
...options,
header,
success(res) {
// 响应拦截器,所有接口获取数据之前,都会先执行这里
// 1. 统一的错误处理
if (res.statusCode != 200) {
wx.showToast({
title: '服务器异常,请联系管理员',
})
}
reslove(res)
},
fail(err) {
reject(err)
}
})
})
}
export function get(url, options = {}) {
return request({
url,
...options
})
}
export function post(url, data, options = {}) {
return request({
url,
data,
method: "POST",
...options
})
}
使用 封装的http index.js中 引入
import { post } from "../../utils/http";
import { get } from "../../utils/http";
post('https://showme2.myhope365.com/api/login',
{
username:this.data.userName,
password:this.data.passWord,
rememberMe:true
}
).then(res => {
console.log(res);
})
get(`https://showme2.myhope365.com/api/cms/article/open/detail/${options.id}`).then(res => {
console.log(res.data.data);
this.setData({
content: res.data.data
})
})