vue中使用axios最详细教程

前提条件:vue-cli 项目

安装:

npm axios from 'axios'

较科学的封装好的axios:(new-axios.js)

import axios from 'axios'
import { Notify } from 'vant';
// import Vue from 'vue'
// import store from '@/store'  // 我此项目没有用到vuex,所以vuex代码的都注释了,需要的自己打开使用

// import {ACCESS_TOKEN} from '@/store/mutation-types'

// 创建 axios 实例
const requests = axios.create({
  baseURL: process.env.VUE_APP_API, // 基础url,如果是多环境配置这样写,也可以像下面一行的写死。
  // baseURL: 'http://168.192.0.123',
  timeout: 6000 // 请求超时时间
})
 
// 错误处理函数
const err = (error) => {
  if (error.response) {
    const data = error.response.data
    // const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
        Notify({ type: 'danger', message: data.message||data.msg });
    }
    if (error.response.status === 401) {
        Notify({ type: 'danger', message: '你没有权限。' });
      // if (token) {
      //   store.dispatch('Logout').then(() => {
      //     setTimeout(() => {
      //       window.location.reload()
      //     }, 1500)
      //   })
      // }
    }
  }
  return Promise.reject(error)
}

// request interceptor(请求拦截器)
requests.interceptors.request.use(config => {
//   const token = Vue.ls.get(ACCESS_TOKEN)
  const token = localStorage.getItem('token')
  if (token) {
    config.headers['token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor(接收拦截器)
requests.interceptors.response.use((response) => {
  const res = response.data
  if (res.code !== 0&&res.code!==200) { 
    Notify({ type: 'danger', message: res.message||res.msg });
    // 401:未登录;
    if (res.code === 401||res.code === 403||res.code===999) {
      Notify({ type: 'danger', message: '请登录'});
    }
    return Promise.reject('error')
  } else {
    return res
  }
}, err)

export default {
  requests
}

main.js 引入,添加到vue原型

import requests from '@s/basejs/new-axios.js'   // 记得改为你的路径
Vue.prototype.rq = requests  // 此处命名为rq,你可以改

使用

this.rq.get('/api/product/get?productChannelId='+this.productChannelId).then(res=>{
    console.log(res)
})

// 传对象参数
// get请求记得加params
this.rq.get('/api/product/get,{params:{name:'abc'}}).then(res=>{
    console.log(res)
})

this.rq.post('/api/product/get,{name:'abc'}).then(res=>{
    console.log(res)
})

 

以下步骤一般不需要

开发环境如果要跨域,解决跨域问题(设置代理):vue-cli 3.0的在 package.json  同级目录新建一个 vue.config.js 文件,加入下面代码,其他版本找到配置文件的devServer加入代码

module.exports = {
    //axios域代理,解决axios跨域问题
    baseUrl: '/',
    devServer: {
        proxy: {
            '': {
                target: 'http://192.168.0.108:8090',
                changeOrigin: true,
                ws: true,
                pathRewrite: {

                }
            }
        }
    }
}

修改完后记得重启项目应用配置

 

这博客是我博客园的第一篇博客,那时候刚出来工作,所以旧版封装得有点烂,抱歉

基于这篇博客是我博客中评论最多的一篇(有点惨)所以下定决心改版一次(2020-3-13)

不懂的可以留言,我们一起探讨

如果有帮助到你,希望你也能帮助下我,点下赞或者收藏

 

posted @ 2018-10-25 23:42  醉梦者  阅读(185187)  评论(12编辑  收藏  举报