微信小程序接口封装

api/request.js      api与pages同级

const baseUrl = '填写对应的接口地址'; // 基础 API 地址

// 封装请求方法

const request = (url, method, data) => {

    return new Promise((resolve, reject) => {

        // wx.showLoading({

        //     title: '加载中...', // 显示的加载文字

        //     mask: true // 遮罩层,防止用户操作

        // });

       

        let header = {

          'content-type': 'application/json',

        };

        header['Authorization'] = 'dswazsda888888888888888';  // 标准写法

      

        wx.request({

            url: `${baseUrl}${url}`,

            method: method,

            data: data,

            header: header,

            success: (res) => {

                // 判断是否请求成功

                if (res.statusCode === 200) {

                    /esolve(res.data); // 请求成功,返回数据

                } else {

                    wx.showToast({

                        title: `请求失败: ${res.data.message || '未知错误'}`, // 显示错误提示

                        icon: 'none',

                        duration: 2000

                    });

                    reject(res.data); // 请求失败,返回错误信息

                }

            },

            fail: (err) => {

                wx.showToast({

                    title: `请求失败: ${err.message || '未知错误'}`, // 显示错误提示

                    icon: 'none',

                    duration: 2000

                });

                reject(err); // 请求失败,返回错误信息

            },

            complete: () => {

                // wx.hideLoading(); // 隐藏加载框

            }

        });

    });

};

// 封装 GET 请求

const get = (url, data, ) => {   return request(url, 'GET', data);  };

// 封装 POST 请求

const post = (url, data) => {  return request(url, 'POST', data); };

// 导出请求方法

module.exports = {

    get,

    post,

    baseUrl

};

使用方式

import http from '../../api/request'

  http.post('/user/login',data).then(res => {

            console.log('res--', res)

        })

        .catch(err => {

            console.log('发送请求失败', err);

        });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值