• vue中如何封装axios及如何使用


    axios安装可参考官网,这里就不多说了,还是直接进入正题

    vue中如何封装axios以及如何使用?

    首先在src/api下新建service.js,具体代码如下:

    import axios from 'axios';
    import { Message,MessageBox } from 'element-ui';
    import store from '../store';
    import { baseUrl } from 'config'
    // import { getToken } from '';
    
    window.temp=true;
    
    axios.defaults.withCredentials=true;//让ajax携带cookie
    
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    
    // 创建axios实例
    const service = axios.create({
      // baseURL: process.env.BASE_API, // api的base_url
      timeout: 300000, // 请求超时时间
      /***如果qs没有stringify,将下面方法打开才能提交form,只在post时生效 **/
      transformRequest: [function (data) {
        // Do whatever you want to transform the data
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        // console.log("ret");
        // console.log(ret);
        return ret;
      }]
    });
    
    // request拦截器
    service.interceptors.request.use(config => {
    
      let token = store.getters.token;
      // console.log(token)
      if (store.getters.token) {
        config.headers['X-Token'] = token; // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
      }
      config.headers['X-SysCode'] = 'stfinance'; //让每个请求携带SysCode,请根据实际情况自行修改
    
      return config;
    }, error => {
      // Do something with request error
      console.log(error); // for debug
      Promise.reject(error);
    })
    /**=======================================**/
    
    // respone拦截器
    service.interceptors.response.use(
      // response => response,
      /**
       * 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页
       * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中,
       */
      response => {
        // return response.data;
        // console.log({response})
    
        const res = response.data;
        if (res.code !== 200) {
          Message({
            message: res.msg,
            type: 'error',
            duration: 5 * 1000
          });
        }
    
        // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
        if (res.code === 503) {
          if(window.temp){
            window.temp=false;
            MessageBox.confirm('你的会话已失效', '确定登出', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning',
         
            }).then(() => {
              window.temp=true;
              window.clearInterval(window.interval);    //清除计时器
              sessionStorage.removeItem('userInfo');    //清除用户信息
              store.commit('logOut');    //注销
              location.reload(); // 为了重新实例化vue-router对象 避免bug
             
              
            }).catch(() => {       
              
            });
          }
        }
        return response.data;
    
      },
      /**接口交互错误是处理,如果特殊错误,可对message进行修改**/
      error => {
        // console.log(error.response.code);//  debug
        let message = error.message;
        console.log(error);
        if (error.response.code == 500) {
          message = "请求异常";
        }
        if (error.response.code == 504) {
          message = "服务器异常";
        }
        if (error.response.code == 404) {
          message = "找不到服务内容";
        }
    
        /**错误弹框,仅在element-ui适用,如果使用其他前端框架(如手机端的),要相应进行修改**/
        Message({
          message: message,
          type: 'error',
          duration: 5 * 1000
        });
        return Promise.reject(error);
      }
    
    )
    
    export default service;

    如果你希望生产环境和开发环境使用不同上下文的话可以在src/api下新建两个文件config.dev.js和config.prod.js,

    config.dev.js代码如下:

    export const baseUrl = "/project-dev"

    config.prod.js代码如下:

    export const baseUrl = "/project-prod"

    注意:此时需在config/index.js文件配置两个代理环境,具体配置如下:

    const path = require('path')
    
    module.exports = {
      dev: {
        // Paths
        env: require('./dev.env'),
        autoOpenBrowser: true,
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
          '/project-dev': {
            target: 'http://58.100.1.101:8080/',        //开发环境
            changeOrigin: true,
            pathRewrite: {
              '^/project-dev': '/project-dev'
            }
          },
          '/project-prod': {
            target: 'http://www.xxxxx.com/',        //生产环境
            changeOrigin: true,
            pathRewrite: {
              '^/project-prod': '/project-prod'
            }
          },
        },
    
        // Various Dev Server settings
        host: '', // can be overwritten by process.env.HOST
        port: 8090, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
        
      },
    
      build: {
        env: require('./prod.env'),
        // Template for index.html
        index: path.resolve(__dirname, '../dist/index.html'),
        // Paths
        assetsRoot: path.resolve(__dirname, '../dist'),
        assetsSubDirectory: 'static',
        assetsPublicPath: '/project/',
    
        /**
         * Source Maps
         */
    
        productionSourceMap: false,
        // https://webpack.js.org/configuration/devtool/#production
        //devtool: '#source-map',
    
        // Gzip off by default as many popular static hosts such as
        // Surge or Netlify already gzip all static assets for you.
        // Before setting to `true`, make sure to:
        // npm install --save-dev compression-webpack-plugin
        productionGzip: false,
        productionGzipExtensions: ['js', 'css'],
    
        // Run the build command with an extra argument to
        // View the bundle analyzer report after build finishes:
        // `npm run build --report`
        // Set to `true` or `false` to always turn it on or off
        bundleAnalyzerReport: process.env.npm_config_report
      },
      cssSourceMap: false
    
    }

    然后在src/api下新建login.js,具体代码如下:

    import service from './service'
    import { baseUrl } from 'config'
    
    
    //登录
    export function login(data) {
        let uri = baseUrl+'/user/login';
        return service ({
          url: uri,
          method: 'post',
          data: data
        });
      }

    此时可以在项目里调用之前封装的axios实例对象,具体引用如下:

    import * as api from "@/api/login";
    
    api.login({user:'user',password:'123456'}).then(res=>{
       if(res.code==200){
         //你需要做的事情     
        } 
    })
  • 相关阅读:
    mySQL教程 第1章 数据库设计
    数学符号大全
    C# 正则表达式 判断各种字符串(如手机号)
    C# 面向对象编程
    博客园 网址
    优化正则表达式的诀窍
    hdu 1596 floyd
    poj3259,简单判断有无负环,spfa
    hdu 1496 hash
    hdu 1429 bfs+二进制状态压缩
  • 原文地址:https://www.cnblogs.com/yanganglanyu/p/10724208.html
Copyright © 2020-2023  润新知