uniCloud——使用公共模块

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, "更新结果")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值