we.request请求封装
第一步在utils下面创建一个http.js,
let sUrl = "https://www.baidu.com";
function getData (url, data, nb) {
wxrequest({
url: sUrl + url,
data: data,
method: 'post',
header: {
// "ContentType": "json", //get请求时候"ContentType": "applicationwwwformurlencoded", //POST请求的时候这样写
'token': wx.getStorageSync('token')
},
success: functionres) {
returntypeof nb == "function" && nb(res.data)
},
fail: functionres) {
returntypeof nb == "function" && nb(res.data)
}
})
}
module.exports = {
req: getData
}
第二步在app.js引入
let http = require ('utils/http.js')
//封装请求res: {
req: http.req //这里配置我们需要的方法
},
然后在你需要的页面直接应用
letdata = {
}//data是你要传的参数
app.res.req('app-web/userproject/list', data, (res) => {
})
5 回复
/**
* post 请求
* [@param](/user/param) {String} path 请求url,必须
* [@param](/user/param) {Object} params 请求参数,可选
* [@param](/user/param) {String} method 请求方式 GET | POST,默认为 POST
* [@param](/user/param) {Object} option 可选配置,如设置请求头 { headers:{} }
* [@param](/user/param) {Boolean} option 可选配置,是否显示‘加载中...’的toast,默认显示
*
* option = {
* headers: {} // 请求头
* }
*
**/
// 获取接口地址
const _getPath = path => (`https://xxx.xxx.com${path}`)
// 封装接口公共参数
const _getParams = (data = {}) => {
const timestamp = Date.now()
const token = util.getStorageSync('token') || ''
const version = data.version
const sign = data.sign || util.md5(version+timestamp)
return Object.assign({}, {
timestamp,
token,
sign,
deviceId,
version
}, data)
}
export const postAjax = (path, params) => {
const url = _getPath(path)
const data = _getParams(params)
// 处理请求头
const headers = util.extend(
true, {
"content-type": "application/x-www-form-urlencoded"
},
headers
);
const method = 'POST'
return new Promise((resolve, reject) => {
my.request({
url,
method,
data,
headers,
success: (res) => {
resolve(res.data)
},
fail: function(res) {
reject(res.data)
},
complete: function(res) {
}
});
})
}
let postData = {
townId: xxx
}
app.postAjax(’/api.xxx.com’, postData).then((res) => {})