小程序请求封装
Posted 远方_未至
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了小程序请求封装相关的知识,希望对你有一定的参考价值。
创建请求文件http.js
var api_base_url = "this is url"; export default function ({ url, data = {}, method = "GET" }) { return new Promise((resolve, reject) => { let contentType = method == ‘POST‘ ? ‘application/x-www-form-urlencoded‘ : ‘application/json‘; wx.request({ url: api_base_url + url, method: method, data: data, header: { "content-type": contentType, }, success: (res) => { const code = res.statusCode.toString(); if (code.startsWith(‘2‘)) { resolve(res.data) console.log("success", res.data) } else { reject(res.data) console.log("error", res.data) } }, fail: (err) => { console.log("fail", err) } }) }) }
创建公共接口文件 api.js
import http from ‘./http.js‘ function getSuccessData(params) { return http({ method: ‘GET‘, url: ‘url‘, data: params }) } function postFormData(params){ return http({ method: ‘POST‘, url: ‘url‘, data: params }) } export { getSuccessData, postFormData }
使用
import { getSuccessData, postFormData } from ‘../../utils/api.js‘ Page({ data: {}, onLoad: function(options) { this.getData() }, //获取数据 getData() { let data = { utoken: "utoken_e6edde9df7cb836b2ceb04b2228505c0", i: 170 } getSuccessData(data).then(result => { console.log(result) return postFormData({id: "11"}).then((res)=>{ console.log(res) }) }) }, onReady: function() {}, onShow: function() {}, onHide: function() {}, onUnload: function() {}, onPullDownRefresh: function() {}, onReachBottom: function() {}, onShareAppMessage: function() {} })
以上是关于小程序请求封装的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段14——Vue的axios网络请求封装