在vue中如何使用axios发送请求

axios是一个基于promise的http库,可以发送get,post请求(axios对ajax的封装),
正由于Vue,React的出现,促使了axios轻量级库的出现

直接使用会报错,需要下载axios,
下载安装命令npm install --save axios

使用axios在vue中发送ajax请求

  • get方式
    // 访问github的search接口
      let url = `https://api.github.com/search/repositories?q=${
     this.queryName}`;
      axios.get(url).then(
        // 当请求成功时触发此函数,参数response即是接收到的数据
        response => {
    
          // console.log(response.data.items);//直接获取数据跨域报错

          // 我们要取的接口中的数据在数组中,而数组外面又被对象包含着
          // 先定义一个变量转存一下数据对象
          let result = response.data;
          console.log(result);

          // 再用一个数组转存一下数组
          let array = result.items[0]; //去数组中第一条数据
          console.log(array);

          this.reqName = array.name;
          this.reqUrl = array.html_url;

        },
        // 如果接口有问题时触发此函数,进行处理
        err => {
   
          console.log("接口出错了" + err);
        
        }).catch(error => {
    //如果请求出错触发此函数,捕获错误信息
        console.log("请求过程出错了" + error);

      });
  • post方式
      axios.post('/user',{
    
        firstName:"AA",
        lastName:"aa"
      }).then(response=>{
   
        console.log(response);
      }).catch(function(error){
   
        console.log("请求出错了");
      });
  • 执行多个并发请求
function getUser(){
   
   return axios.get(url); //返回一个get请求
}
function postUser(){
   
   return axios.post(url,{
   a:1}); //返回一个post请求
}
axios.all([getUser(),postUser()]).then().catch(){
   };
}
  • 配置对象方式
      axios({
   
        methods:"post",
        url:"/user/abc"
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值