封装原生的微信小程序ajax请求

    技术2022-07-10  123

    使用promise封装原生的微信小程序ajax请求

    这里需要注意的一点是:在进行数据请求的时候,一定要在微信开发者工具详情里面

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HCjBuTUy-1593522567511)(C:\Users\l\AppData\Roaming\Typora\typora-user-images\image-20200630205906404.png)]

    这里面一定要勾选上,不然会报错,数据请求不到

    原生自己封装

    /** * 使用promise封装原生的微信小程序ajax请求 * @param {string} url 请求路径 * @param {object} params 请求参数 * @param {string} methods 请求类型 * @param {object} header 请求头 */ const app = getApp() const hosturl = app.globalData.host module.exports = (url, params = {}, methods = "GET", header = {}) => { return new Promise((resolve, reject) => { wx.request({ url:hostrul+url //仅为示例,并非真实的接口地址 methods, data: params, success: resolve, fail: reject }) }) }

    使用:

    const fetch = require("../../utils/fetch")

    网上封装的比较好的原生微信小程序ajax请求

    const app = getApp() const request = (url, options) => { return new Promise((resolve, reject) => { wx.request({ url: `${app.globalData.host}${url}`, method: options.method, data: options.method === 'GET' ? options.data : JSON.stringify(options.data), header: { 'Content-Type': 'application/json; charset=UTF-8', 'x-token': 'x-token' // 看自己是否需要 }, success(request) { if (request.data.code === 2000) { resolve(request.data) } else { reject(request.data) } }, fail(error) { reject(error.data) } }) }) } const get = (url, options = {}) => { return request(url, { method: 'GET', data: options }) } const post = (url, options) => { return request(url, { method: 'POST', data: options }) } const put = (url, options) => { return request(url, { method: 'PUT', data: options }) } // 不能声明DELETE(关键字) const remove = (url, options) => { return request(url, { method: 'DELETE', data: options }) } module.exports = { get, post, put, remove }

    封装flyio

    步骤:

    1.下载:(一开始一定要初始化一下,让项目变成一个node项目)

    npm init -y npm i flyio -S (下载flyio的包)

    2.下载下来之后,把包单独拎出来,不要放在nodemodel里面

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KoTVDnCp-1593522567515)(C:\Users\l\AppData\Roaming\Typora\typora-user-images\image-20200630203813241.png)]

    3.封装:

    // 1. 引入flyio import Fly from './flyio/dist/npm/wx' // 2. 实例化 const fly = new Fly() const host = getApp().globalData.host // 添加请求拦截器 fly.interceptors.request.use( (request) => { wx.showLoading({ title: '加载中', mask: true }) // console.log(request) // request.headers["X-Tag"] = "flyio"; // request.headers['content-type']= 'application/json'; request.headers = { 'X-Tag': 'flyio', 'content-type': 'application/json' } let authParams = { // 公共参数 'categoryType': 'SaleGoodsType@sim', 'streamNo': 'wxapp153570682909641893', 'reqSource': 'MALL_H5', 'appid': 'string', 'timestamp': new Date().getTime(), 'sign': 'string' } request.body && Object.keys(request.body).forEach((val) => { if (request.body[val] === '') { delete request.body[val] }; }) request.body = { ...request.body, ...authParams } return request }) // 添加响应拦截器 fly.interceptors.response.use((response) => { wx.hideLoading() return response.data// 请求成功之后将返回值返回 }, (err) => { // 请求出错,根据返回状态码判断出错原因 console.log(err) wx.hideLoading() if (err) { return '请求失败' }; } ) // 3. 配置根路径 fly.config.baseURL = host export default fly

    4.使用

    import api from "../../api/index" //引入 async getSlides() { //进行数据请求 const res = await api.get("/slides") this.setData({ slides: res }) },
    Processed: 0.013, SQL: 9