ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

vue axios的使用方法

2021-07-22 22:32:04  阅读:115  来源: 互联网

标签:axios const get res token vue 方法 response


https://www.cnblogs.com/nogodie/p/9853660.html
前提条件: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: {

            }
        }
    }
}

}

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

 

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

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

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

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

标签:axios,const,get,res,token,vue,方法,response
来源: https://www.cnblogs.com/cn-oldboy/p/15046732.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有