1.文档地址
微信官方文档:wx.request网络请求
2.项目使用
根目录下新建utils =>request.js ,作为请求通用库
const DEV_URL = 'http://localhost:22667'
const PRODUCT_URL = 'http://xx.xx.xx.xx:22667'
let SERVER_URL = DEV_URL
let request = (method, url, data) => {
return new Promise((resolve, reject) => {
let headers = {}
headers['Accept'] = 'application/json, text/plain, */*'
wx.getStorage({
key: 'token'
}).then(res => {
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 => {
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 => {})
})
}
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
}
|