• uni-app 请求封装


    1.创建一个http.js 

    ​
    const baseUrl = 'http://192.168.1.188:8080'; 
    const httpRequest = (opts, data) => {
    let httpDefaultOpts = {
    url: baseUrl+opts.url,
    data: data,
    method: opts.method,
    header: opts.method == 'get' ? {
    'X-Requested-With': 'XMLHttpRequest',
    "Accept": "application/json",
    "Content-Type": "application/json; charset=UTF-8"
    } : {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    dataType: 'json',
    }
    let promise = new Promise(function(resolve, reject) {
    uni.request(httpDefaultOpts).then(
    (res) => {
    resolve(res[1])
    }
    ).catch(
    (response) => {
    reject(response)
    }
    )
    })
    return promise
    };
    //带Token请求
    const httpTokenRequest = (opts, data) => {
    let token = "";
    uni.getStorage({
    key: 'token',
    success: function(ress) {
    token = ress.data
    }
    });
    //此token是登录成功后后台返回保存在storage中的
    let httpDefaultOpts = {
    url: baseUrl+opts.url,
    data: data,
    method: opts.method,
    header: opts.method == 'get' ? {
    'Token': token,
    'X-Requested-With': 'XMLHttpRequest',
    "Accept": "application/json",
    "Content-Type": "application/json; charset=UTF-8"
    } : {
    'Token': token,
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    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,
    httpTokenRequest    
    }


    2.将http.js引入

    import http from '@/components/utils/http.js';

    let opts={
                            url: '/api/device/add',
                            method: 'post'
                        };
                        let param={
                            deviceId:this.deviceCode,
                            deviceName:this.deviceName
                        };
                        http.httpTokenRequest(opts, param).then(res => {
                            console.log(res.data);
                           //打印请求返回的数据
                            
                        },error => {console.log(error);}) 
  • 相关阅读:
    推荐阅读20100603
    [ASP.NET4之旅]Circular file references are not allowed
    满园尽是503,记曾经的一次IIS 7性能考验
    VS2010小Bug:找不到System.Web.Extensions.dll引用
    VS2010奇异Bug:三个中文符号在CSS文件中轻松让VS2010崩溃
    推荐阅读20100528
    Windows平台网站文件同步备份解决方案——cwRsyn
    推荐阅读20100803
    在IE8中使用建行企业网银的解决方法
    博客园已经用上NorthScale Memcached Server
  • 原文地址:https://www.cnblogs.com/plBlog/p/11431410.html
Copyright © 2020-2023  润新知