微信全局封装ajax请求 app.js入口文件
一、当需要与后端接口开发时,根据开发文档来是需要封装ajax请求
1.入口app.js文件配置
// app.js 是项目的入口文件,所以必须调用App(这个方法的名字是固定的)方法,所有的js代码都应该在这个方法中进行编写 App({ // 是一个全局生命周期,而且只有这一个,应用注册生命周期 onLaunch() { console.log('-------------------- onlaunch生命周期') }, baseUrl: 'http://www.shuiyue.info:12600', // 在这里定义一个方法,它就应该是一个全局方法 Ajax(req) { if (!req.url) throw new Error('url参数必传') return new Promise(resolve => { wx.request({ // 如果是接口文档上IP域名地址为:locahost或则127.0.0.1都是本地地址,这个时候需要问后端要具体的地址 // http://www.shuiyue.info:12600 不在以下 request 合法域名列表中,请参考文档:https://developers.weixin.qq.com // 发起请求的接口必须在微信小程序平台进行配置过的域名 // 在后台管理平台中 -> 开发 -> 开发管理 -> 开发设置 -> 服务器域名 // 域名配置每个月有配置次数限制 50次;http协议只能是二代协议(https),并且是国际认证的SSL证书,自己做的证书没有用 // 在开发的时候,可以通过配置来实现http接口调用(在开发工具的右上角 详情菜单 本地设置 勾选开发不校验域名);如果要发布应用,必须是https,否则调用不会成功 url: req.url, method: req.method || 'GET', data: req.data || {}, // 得到的data对象是一个response对象,不是后端返回的数据对象,response对象的data对象才是后端返回数据 // success(data) { success({data}) { // console.log('--------------------------- success') // console.log(this) // console.log(_this) // console.log(data) resolve(data) }, fail: () => { // console.log(this) resolve({code: 400, message: '接口调用失败'}) }, complete: () => { // try {} catch {} finally {} // console.log(this) // console.log('-------------------------------- complate') } }) }) } })
2.ajax编写
App({ //注册生命周期 onLaunch(){ console.log('----onlaunch生命周期') } , baseUrl:'http://www.shuiyue.info:12600', Ajax(req){ if(!req.url) throw new Error('url参数必传') return new Promise(resolve =>{ wx.request({ url:req.url, method:req.method || 'GET', data:req.data || {}, success({data}){ resolve(data) }, fail:()=>{ resolve({code:400,message:'接口调用'}) }, complete:()=>{ //try {} catch {} finally{} } }) }) } })

浙公网安备 33010602011771号