uniapp接口請求(第二種)


1. 新建config文件夾=>index.js文件
文件內容

1. 新建api文件夾=>api.js文件夾
文件內容

 1 import baseURL from '../config/index.js'; //引入網址前綴文件
 2 // 得到傳來的參數 用params來接收
 3 module.exports = (params) => {
 4     const URL = baseURL.baseURL;
 5     let url = URL + params.url;
 6     let method = params.method;
 7     let header = params.header || {};
 8     let data = params.data || {};
 9     // 請求方式 GET POST
10     if (method) {
11         method = method.toUpperCase()
12         if (method === 'POST') {
13             header = {
14                 "content-type": "application/x-www-form-urlencoded"
15             }
16         }
17     }
18 
19     //  發起請求 加載動畫
20     if (!params.hideLoading) {
21         uni.showLoading({
22             title: '加載中'
23         })
24     }
25 
26     // 發起網絡請求
27     uni.request({
28         url: url,
29         method: method || 'GET',
30         header: header,
31         data: data,
32         dataType: 'json',
33         sslVerify: false, //是否驗證ssl證書
34         success: (res) => {
35             //  當statusCode 等於200的時候是請求成功了,請求到的數據應該回傳給調用的地方,在調用的地方拿到數據后再進行處理
36             if (res.statusCode && res.statusCode != 200) {
37                 uni.showModal({
38                     content: res.msg
39                 })
40                 return;
41             }
42             typeof params.success == "function" && params.success(res.data)
43         },
44         fail: err => {
45             uni.showModal({
46                 content: err.msg
47             })
48             //  在請求失敗的fail里寫上對應的處理,失敗的時候把失敗信息回傳給調用的地方
49             typeof params.fail == "function" && params.fail(err.data);
50         },
51         complete: (e) => {
52             console.log("請求完成");
53             // 關掉請求的loading
54             setTimeout(function() {
55                 uni.hideLoading()
56             }, 1200);
57             typeof params.complete == "function" && params.complete(e.data);
58             return;
59         }
60     })
61 }

 

3. 在main.js文件夾中全局注冊引用
`import http from './utils/api/api.js';`
`Vue.prototype.http = http;`

4.使用方法

參考自“油麥菜大佬”的uniapp封裝網絡請求
地址鏈接https://www.cnblogs.com/easth/p/uniapp_http.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM