微信小程序请求封装

1.页面根目录下新建api 文件夹,作用发起请求

2. api文件夹下建一个http.js 用来发送promise请求

import baseUrl from "./baseUrl"

var fun = function (config) {
    return new Promise((resolve, reject) => {
        wx.request({
            //url: 'url',//路径
            url: baseUrl + config.url,
            // timeout: 5000, //设置请求时间
            // data: {
            //     // 存放的数据
            // },
            // data:config.data,
            method:config.method,
            // method: "GET", //数据请求方式
            //   header:"",  请求头设置
            success: res => {
                resolve(res)
                console.log('res数据成功了', res);
            }
            // fail(err) {
            //     console.log('err数据请求失败了', err);
            // },
            // complete: res => {
            //     console.log("请求完成后的参数");
            // }
        })
    })
}
export default fun

http.sj 同级新建js文件 baseUrl ,用来设置共同的请求头

export default "https://autumnfish.cn"

api 下新建 index文件夹 文件夹下 设置 index.js文件

import http from "../http"

function getList(data) {
    return  http({
        url: '/top/artists',// 放入除了baseUrl 的路径
        data ,//参数,
        method: "GET", 

    })
}
export  {getList}

在需要用到的地方

导入 
import {
    getList
}
from "../../api/index/index"
    onLoad(options) {
        getList({里面放请求的参数}).then(res => console.log(res.data.artists))
        
    },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容