微信小程序 wx.request 封装
配置域名
一般情况下,项目中的域名前缀都是配置在 app.js 中
App({
onLaunch: function() {
},
globalData: {
userInfo: null,
baseurl:"http://127.0.0.1:8000/api"
}
})
封装 wx.request
在utils文件夹中新建一个request.js文件,在此文件中用来封装request方法
const app = getApp()
const request = (url, options) => {
return new Promise((resolve, reject) => {
wx.showLoading({
title: '加载中',
})
wx.request({
url: `${app.globalData.host}${url}`,
method: options.method,
data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
header: {
'Content-Type': 'application/json; charset=UTF-8',
'x-token': 'x-token' // 看自己是否需要
},
success(request) {
if (request.data.code === 2000) {
resolve(request.data)
} else {
reject(request.data)
}
},
fail(error) {
reject(error.data)
},
complete: () => {
setTimeout(() => {
wx.hideLoading();
}, 100);
}
})
})
}
const get = (url, options = {}) => {
return request(url, { method: 'GET', data: options })
}
const post = (url, options) => {
return request(url, { method: 'POST', data: options })
}
const put = (url, options) => {
return request(url, { method: 'PUT', data: options })
}
// 不能声明DELETE(关键字)
const remove = (url, options) => {
return request(url, { method: 'DELETE', data: options })
}
module.exports = {
get,
post,
put,
remove
}
管理api接口
在utils文件夹中再创建一个api.js文件,用来管理api请求
const getIndexPage = '/index' // 获取首页数据
module.exports={
getIndexPage
}
使用封装后的api接口
import api from "../../utils/request.js"
import {getIndexPage} from "../../utils/api.js"
onLoad: function (options) {
var that = this
api.get(getIndexPage, {
data:""
}).then(res=>{
console.log(res)
that.setData({
index:res.data
})
}).catch(err=>{
console.log(err)
})
},
post 请求就是api.post()...,get 请求就是api.get()...