• 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

  • 相关阅读:
    leetcode35. search Insert Position
    leetcode26.Remove Duplicates from Sorted Array
    leetcode46.Permutation & leetcode47.Permutation II
    leetcode.5 Longest Palindromic Substring
    [转载] C++中new和malloc的区别
    [转载] C++中的自由存储区和堆
    xCode8以及iOS10 的新特性
    cell上添加倒计时,以及时差问题的解决
    cell的复用机制
    iOS 懒加载模式
  • 原文地址:https://www.cnblogs.com/dagongren/p/14011377.html
Copyright © 2020-2023  润新知