axios在vue-cli构建项目中的使用

1. 安装

npm install --save axios vue-axios

2. 引入

// main.js
import Vue from 'vue'
import router from './router'
import App from './App.vue'
import axios from 'axios' // 1. 引入

// 2. 配置请求的根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/'

// 3. 通过axios 请求拦截器 添加token 需要授权的 API ,必须在请求头中使用 `Authorization` 字段提供 `token` 令牌
axios.interceptors.request.use(config => {
    
    
  config.headers.Authorization = window.sessionStorage.getItem('token')
  // 在最后必须return config
  return config
})

// 4. axios 响应拦截器 设置返回的值
axios.interceptors.response.use(function (res) {
    
    
  return res.data
}, function (err) {
    
    
  console.log(err)
})

// 5. 挂载到vue中
Vue.prototype.$http = axios

3. 使用

methods: {
    
    
    async getMenuList () {
    
    
      // 获取左侧菜单
      const res = await this.$http.get('menus') // 返回的是个promise 可以使用asyn/await
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.menulist = res.data
    },
}

猜你喜欢

转载自blog.csdn.net/tyoubinn/article/details/109008092