欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信小程序封裝request請(qǐng)求的詳細(xì)過程

 更新時(shí)間:2025年01月02日 10:30:38   作者:25號(hào)底片~  
文章介紹了如何在微信小程序中封裝request請(qǐng)求,首先定義了一個(gè)request.js類,其中url是通過全局變量app.globalData.position和傳遞的url地址拼接而成,文章還提到了POST和GET請(qǐng)求的使用方法,并鼓勵(lì)讀者繼續(xù)瀏覽相關(guān)文章,感興趣的朋友一起看看吧

1、定義一個(gè)request.js類

// utils/request.js
const app = getApp();
function requestWithToken(url, method = 'GET', data = {}) {
    return new Promise((resolve, reject) => {
        // 發(fā)送請(qǐng)求
        wx.request({
            url: app.globalData.position + url,
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            method: method,
            data: data,
            success: res => {
                if (res.statusCode === 200) {
                    resolve(res.data);
                } else {
                    // 其他錯(cuò)誤處理
                    wx.showToast({
                        title: '請(qǐng)求失敗,請(qǐng)稍后重試',
                        icon: 'none'
                    });
                    reject(new Error('Request failed'));
                }
            },
            fail: err => {
                reject(err);
            }
        });
    });
}
// 導(dǎo)出封裝的請(qǐng)求函數(shù)
module.exports = {
    requestWithToken
};

這里的 url: app.globalData.position + url,,

app.globalData.position:是在全局變量定義的position,例如 http://域名/api/

后者url:是傳遞的url地址

2、頁(yè)面執(zhí)行請(qǐng)求 POST請(qǐng)求

//封裝的請(qǐng)求方法
requestWithToken('Homepage/sel_YearInfo', 'POST', formData)
.then(response => {
    console.log('Form submitted successfully:', response);
    that.setData({
        monthinfo:response.info
    })
})
.catch(error => {
    console.error('Error submitting form:', error);
    // 處理錯(cuò)誤
});

GET請(qǐng)求

requestWithToken('Homepage/sel_YearInfo', 'GET')
      .then(response => {
          console.log('Protected resource:', response);
          // 處理響應(yīng)數(shù)據(jù)
      })
      .catch(error => {
          console.error('Error:', error);
          // 處理錯(cuò)誤
      }

到此這篇關(guān)于微信小程序封裝request請(qǐng)求的文章就介紹到這了,更多相關(guān)微信小程序封裝request請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論