隐藏

vue 安装与使用axios

发布:2022/3/18 11:21:30作者:管理员 来源:本站 浏览次数:710

npm install axios --save          //安装axios

使用axios

引入 main.js 文件引入(全局引入)

import axios from 'axios'          //引入axios

 Vue.prototype.$axios = axios;      //把axios挂载到vue上

methods:{

getUser(){

this.$axios({

             method:"post",

             url:" ",

             data:{ }

       }).then( (res)=>{ console.log(res); } )

}   

 }

使用时引入(局部)

import  axios  from 'axios'    或者    const axios=require('axios');

使用:

axios.get('url').then((res)=>{  }).catch((err)=>{ })

axios.post('url',{参数key:'值',参数2:'值'}).then((res)=>{  }).catch((err)=>{  })

axios跨域

在config的 index.js 文件中的dev 属性中找到( 没有的话就添加)属性proxyTable:

proxyTable{

'/api':{

                 //被代理的接口(你要调用的接口域名和端口号)

                   target:"http://61.23.11.122:8080",            

                   changeOrigin:true,

                   pathRewrite:{

                                    '^/api':""        //用  /api  代替target里面的地址               

                           },

                   secure:true          // 如果是https接口,需要配置这个参数

      }

}

在axios里面访问接口时,以 /api/xxx  这种方式只能本地测试环境运行,对正式环境无效(需要配置环境生效)