1.文档地址
2.项目使用
根目录下新建utils
=>request.js
,作为请求通用库
//接口地址
const DEV_URL = 'http://localhost:22667'
const PRODUCT_URL = 'http://xx.xx.xx.xx:22667'
//选用的接口地址,这行代码主要是方便URL地址的统一修改
let SERVER_URL = DEV_URL
//wx.request封装
let request = (method, url, data) => {
return new Promise((resolve, reject) => {
//请求之前先定义请求头
let headers = {}
headers['Accept'] = 'application/json, text/plain, */*'
//从storage中获取token,能拿到说明已登录
wx.getStorage({
key: 'token'
}).then(res => {
//请求头中带上token
headers['Authorization'] = res.data
wx.request({
url: SERVER_URL + url,
method: method,
header: headers,
data: data,
success: res => {
if (res.data.resultCode === 200) {
resolve(res)
} else {
reject(res)
}
},
fail: err => {
reject('请求失败!')
}
})
}).catch(err => {
//因为无token,下面的代码可以跳转到登录页,也可以直接请求
wx.request({
url: SERVER_URL + url,
method: method,
header: headers,
data: data,
success: res => {
if (res.data.resultCode === 200) {
resolve(res)
} else {
reject(res)
}
},
fail: err => {
reject('请求失败!')
}
})
})
})
}
//封装上传文件至特定服务器的接口
let upload = (tempUrl, url) => {
return new Promise((resolve, reject) => {
let header = {}
header['Accept'] = 'application/json, text/plain, */*'
wx.getStorage({
key: 'token'
}).then(res => {
let token = res.data
header['Authorization'] = token
wx.uploadFile({
filePath: tempUrl,
name: 'image',
url: PRODUCT_URL + url,
header: header,
success(res) {
let data = JSON.parse(res.data)
if(data.resultCode === 200) {
resolve(data.data)
} else {
reject(res.message)
}
},
fail(err) {
reject(err)
}
})
}).catch(err => {})
})
}
//对外暴露api,调用request/upload方法,这里的代码也可以单独写到api.js中
const api = {
login: (data) => request('POST', '/api/v1/user/login', data),
register: (data) => request('POST', '/api/v1/user/register', data),
getProfile: () => request('GET', '/api/v1/user/profile'),
goodsSearch: (data) => request('GET', '/api/v1/goods/search', data),
getGoodsDetail: (goodsId) => request('GET', '/api/v1/goods/detail/' + goodsId),
uploadImage: (tempUrl) => upload('POST', tempUrl, '/api/v1/tool/upload'),
updateProfile: (data) => request('/api/v1/user/profile', data),
addCart: (data) => request('POST', '/api/v1/shop-cart/shop-cart', data),
getCart: (paegNumber) => request('GET', '/api/v1/shop-cart/shop-cart/page', paegNumber),
getDefaultAddress: () => request('GET', '/api/v1/address/address/default'),
getAddressList: () => request('GET', '/api/v1/address/address'),
addAddress: (data) => request('POST', '/api/v1/address/address', data),
settleOrder: (data) => request('POST', '/api/v1/order/saveOrder', data),
getOrderList: () => request('GET', '/api/v1/order/order')
}
module.exports = {
api
}