zoukankan      html  css  js  c++  java
  • uni-app 接口封装

    uni-app 的请求接口在官方文档里是这样的

    uni.request({
        url: 'https://www.example.com/request', //仅为示例,并非真实接口地址。
        data: {
            text: 'uni.request'
        },
        header: {
            'custom-header': 'hello' //自定义请求头信息
        },
        success: (res) => {
            console.log(res.data);
            this.text = 'request success';
        }
    });

    在common 中 http.js文档中进行如下封装:

    const baseUrl = '****';    //请求地址
    const httpRequest = (opts, data) => {
        let httpDefaultOpts = {
            url: baseUrl+opts.url,
            data: data,
            beforeSend :function(xmlHttp){
                xmlHttp.setRequestHeader("If-Modified-Since","0"); 
                xmlHttp.setRequestHeader("Cache-Control","no-cache");
            },
            method: opts.method,
            header: opts.method == 'GET' ? {
            'X-Requested-With': 'XMLHttpRequest',
            "Accept": "application/json",
            "Content-Type": "application/json; charset=UTF-8"
        } : {
           'content-type': 'application/x-www-form-urlencoded'
        },
            dataType: 'json',
        }
        let promise = new Promise(function(resolve, reject) {
            uni.request(httpDefaultOpts).then(
                (res) => {
                    resolve(res[1])
                }
            ).catch(
                (response) => {
                    reject(response)
                }
            )
        })
        return promise
    };
    export default {
        baseUrl,
        httpRequest
    }

    在页面中引入http.js

    在需要接口请求的部分可以这样写:

    http.httpRequest({
    					url: '/api/mineralInfo',  //接口地址
    					method: 'POST'   //请求方式
    				},{
    					submitStatus:1   //参数部分
    				}).then(
    					res => {
    						if(res.data.code == "0"){
    							//请求成功
    						}
    					},
    					error => {
    						console.log('网络请求错误,请稍后重试!');
    						return;
    					}
    				);
    

      

  • 相关阅读:
    Unity SceneManager 对场景的操作
    Unity [Tooltip("")]
    Unity WWW下载图片并保存到Unity的Assets下
    C# 集合
    C# 枚举与switch用法
    C# String.Format方法
    C# Thread类 线程优先级
    Unity Gizmos可视化辅助工具
    anacanda
    异常和错误
  • 原文地址:https://www.cnblogs.com/yeziyou/p/13463531.html
Copyright © 2011-2022 走看看