1. 创建公共模块
起个名字创建(可能会提示common不存在,点是创建即可)
2. 公共模块安装依赖,写方法,并导出
const rp = require("request-promise")
const getHttp = async ({
method,
url,
headers,
body
}) => {
method = method ? method.toUpperCase() : "GET"
headers = headers ? headers : {
"content-Type": "application/json"
}
if (method == "GET") {
return await rp({
url,
json: true, //这样就解析成json格式
})
.then(res => {
return res //get请求 必须用Json来解析
})
.catch(err => {
return {
msg: '请求失败GET',
code: 500,
err
}
});
} else if (method == "POST") {
return await rp({
url,
method: "POST",
json: true, //这样就解析成json格式
body,
headers,
})
.then(res => {
return res //就不需要 json.parse了, 会报错
})
.catch(err => {
// return err
return {
msg: '请求失败Post',
code: 500,
err
}
});
}
}
module.exports = {
getHttp
}
3. 其他模块引用公共模块
其他模块右键->管理公共模块->选择项目公共模块,这样就关联搞好了
4. 其他模块使用该公共模块
const asyncFun = require('asyncfun')
var res = ""
var httpInfo = ""
var urlBase = "http://101.37.77.138:3001"
module.exports = {
_before: function() { // 通用预处理器
httpInfo = this.getHttpInfo()
},
//用户登录
async login(body) {
body = JSON.stringify(body) == "{}" ? JSON.parse(httpInfo.body) : body
res = await asyncFun.getHttp({
method: "POST",
url: urlBase + "/login",
body: body
})
return res
},
async updateUserInfo(body) {
body = JSON.stringify(body) == "{}" ? JSON.parse(httpInfo.body) : body
res = await asyncFun.getHttp({
method: "POST",
url: urlBase + "/updateUserInfo",
body: body
})
return res
},
//请求 生成部门 和 部门
async getPart() {
let result = {}
//请求部门
res = await asyncFun.getHttp({
method: "GET",
url: urlBase + "/getPart"
})
result["getPart"] = res.recordset
//请求生成部门
res = await asyncFun.getHttp({
method: "GET",
url: urlBase + "/getSCPart"
})
result["getSCPart"] = res.recordset
return result
},
}
5. 微信小程序端 调用 url 化的接口
res = await asyncWx.request({
url: appInstance.globalData.host + "/updateUserInfo", //updateUserInfo 为里面的函数
header: {
'content-type': 'application/json' // 默认值
},
method: 'POST',
data: {
uNo: this.data.uNo,
uPwd,
uName,
uPart,
uSCPart,
uOldPwd
},
})
console.log(res, "更新结果")