zoukankan      html  css  js  c++  java
  • uniapp之封装一个公共的带token的请求方法

    1 创建一个文件名为config.js

    const baseurl = 'http://xxx:9090/';  //公共接口请求地址
    export default baseurl;

    2 在登录接口返回数据的那步,将token存进缓存中

                     // 存储token
                            uni.setStorage({
                                key: 'token',
                                data: res.data.access_token,
                                success: function () {
                                    uni.getStorage({
                                        key: 'token',
                                        success: function (res) {
                                            console.log(res.data);
                                        }
                                    });
                                }
                            });

     在uni.getStorage  API中打印,会发现已经可以拿到缓存的token数据了

    3 创建一个公共请求文件 requst.js

    如果token不存在,就返回到登录界面。baseurl为公共的接口地址

     import baseurl from './config.js'
    // 公共的请求
     const request = function(options) {
         options.url = baseurl + options.url;
         try {
           const token = uni.getStorageSync('token');
           const username = uni.getStorageSync('username');
           debugger
           if (token) {
             options.header = {
               'Authorization' : 'Bearer ' + token
             };
            }else{
                uni.navigateTo({
                    url: '../../login/login/login' 
                });
                return;
            }
         } catch (err) {
          console.log(err)
        }
        return uni.request(options);
      }
    export default request;

    4 去相应界面使用

      import request from '../../../request.js'               //引进requst方法

      onShow:function(){
                request({
                    url:"message/messages",
                    method:'get',
                    success: function (res) {
                        console.log(res.data);
                    }
                })    
            }
    ————————————————
    版权声明:本文为CSDN博主「web前端_CC」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/CuiCui_web/java/article/details/102746147

  • 相关阅读:
    array and ram
    char as int
    pointer of 2d array and address
    Install SAP HANA EXPRESS on Google Cloud Platform
    Ubuntu remount hard drive
    Compile OpenSSL with Visual Studio 2019
    Install Jupyter notebook and tensorflow on Ubuntu 18.04
    Build OpenCV text(OCR) module on windows with Visual Studio 2019
    Reinstall VirtualBox 6.0 on Ubuntu 18.04
    Pitfall in std::vector<cv::Mat>
  • 原文地址:https://www.cnblogs.com/123poi/p/13361110.html
Copyright © 2011-2022 走看看