小程序api封装
创建api目录,和pages同级
api.js 文件代码
const app = getApp()
const request = (url, options) => {
return new Promise((resolve, reject) => {
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'
},
success(request) {
if (request.data.Code === 200) {
resolve(request.data)
} else {
reject(request.data)
}
},
fail(error) {
reject(error.data)
}
})
})
}
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
}
conf.js 文件代码
const login = '/v1/user/login'
module.exports = {
login
}
在app.js中设置域名
globalData: {
host: 'https://www.xxx.com/api'
}
使用方法:
import api from '../../api/api'
import { login } from '../../api/conf'
onLoad: function (options) {
api.get(login,{
data: data
}).then(res => {
wx.showToast({
title: 'api调用成功',
icon: 'none'
})
}).catch(err => {
wx.showToast({
title: 'api调用失败',
icon: 'none'
})
})
}