vue axios用法

axios

axios 是基于promise的用于浏览器和nodejs的HTTP客户端
特征:
  1. 从浏览器中创建XMLHttpRequest
  2. 从nodejs发出http请求
  3. 支持promise
  4. 拦截 请求 和响应
  5. 转换请求和响应数据
  6. 取消请求
  7. 自动转换json数据
  8. 客户端支持防止CSRF/XSRF攻击
请求方法
  • get 获取数据
  • post 提交数据
  • put更新数据
  • patch 更新数据
  • delete 删除数据
基本用法
get
  axios.get("./dizhi")
  .then(function (res) {
      console.log(res);
  })
  .catch(function(err){
      console.log(err)
  });



  axios.get("./dizhi",{
      params:{
        id : 123
      }
  })
  .then(function (res) {
      console.log(res);
  })
  .catch(function(err){
      console.log(err)
  });

拦截器
请求拦截器 interceptors.requst :是指可以拦截每次或指定HTTP请求,并可修改配置项。
响应拦截器 interceptors.response :可以在每次HTTP请求后拦截住每次或指定HTTP请求,并可修改返回结果项。
//添加请求拦截器
 axios.interceptors.request.use(function(config){
      return config;
  },function(err){
      console.log(err)
  });

vue中axios用法

  1. 安装axios

    • cnpm install axios -S
  2. 安装成功后,在main.js中引用

    import axios from “axios”
      
    
  3. 开始使用请求

    在app.vue 里 script标签中 
        export default{
            mounted(){
              //axios完整写法 // $.get $.post  $.ajax({})
                 axios({
                   url:"请求地址",
                   method:"get",
                   headers:{
                     //请求头信息
               }
             }).then(res=>{
               console.log(res.data)
             })
            }
        }
        //代理服务器只是在开发环境中有效果
    
  4. 在项目的根目录下vue.config.js中配置

        module.exports={
            devSever :{
                open : true
                port : 8090,
                host : 127.0.01
                //代理是一个对象
        
                proxy :{
                    // "/lagou":访问的地址以/lagou开头的才会开启该代理服务
                    target:""//代理的服务地址,
                    changeOrigin : true //是否开启代理
                    pathRewrite:{
                        //对地址进行重写
                        "'/lagou'":""
                    }
                }
            }
        }
    
  5. vue.config.js 修改完后 重启 cnpm run serve

原文地址:https://www.cnblogs.com/zhaoxinran997/p/12346946.html