好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

可能是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: {

                }
            }
        }
    }
}

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

总结

到此这篇关于vue中使用axios最详细教程的文章就介绍到这了,更多相关vue使用axios教程内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

查看更多关于可能是vue中使用axios最详细教程的详细内容...

  阅读:39次