axios发送请求,一篇搞定

1、axios发送请求的方式
简写:

delete和get请求相似,put请求和post请求类似

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 上面的请求也可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
繁写:
// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

繁写没有问题,怎样配置官方文档很清楚;
但是简写的配置反倒不是很全面;

简写配置(携带请求头和参数):

总结:get请求的话就仿照繁写的请求进行一个参数配置。但是如果是post请求的话,就都是对象,然后在对象里进行一个键值对书写

const id = 'xxx';
const token = 'xxxxxxxxxxxxxxxxx';
axios.get("http://xxx/xxx",{
//get请求传入参数的时候,里面传入 params 这个参数,一定要是params。
	//参数列表
       params:{
        id :12345
       }, 
    //请求头配置  
       headers:{ 
         token: token
        }
    }).then((res)=>{
        console.log(res)
       })
    .catch((error)=>{
    console.log(error);
    })

 let refreshToken = localStorage.getItem("token");
  axios
    .post(
      "http://202.101.162.69:8089/proxy/top/api/score/event/addAgentLog",
      //参数列表
      {
        eventId: components.itemiframe.data.data.eventId,
        eventAgent: components.eventAgent,
        type: 2,
        content: components.richtext.press,
      },
      //请求头配置
      {
        headers: {
          Authorization: refreshToken,
        },
      }
    )
    .then((res) => {
      // console.log("fankui",res)
      if (res.data.code == 200) {
        this.$message({
          message: "批示成功",
          type: "success",
          center: "true",
          duration: 500,
          customClass: "press",
        });
      } else {
        this.$message({
          message: "批示失败",
          type: "warning",
          center: "true",
          duration: 500,
          customClass: "press",
        });
      }
      this.richtext.pishi = "";
      this.itemiframepishi.show = false;
    });
//post请求中要在params中携带参数
 const { data: res } = await this.$http.post(
        "/data/tableData/updateData",
        {
          tableDataMap: this.valueObj,
          tableName: this.table_info.name,
        },
        { params: { userId: this.userId } }
      );
      if (res.code !== "200") return this.$message.error("编辑数据失败");
2、axios发送请求的方式获取到的数据进行处理

== 以上例子中用到的 .then .catch==

//无论是简写还是繁写,后面都可以这样直接用then和catch进行回调
axios.get('/user?ID=12345')
 .then(function (response) {
   console.log(response);
 })
 .catch(function (error) {
   console.log(error);
 });

async 和await

  • async作为一个关键字放到函数前面
    • 任何一个async函数都会隐式返回一个promise
  • await关键字只能在使用async定义的函数中使用
    • await后面可以直接跟一个 Promise实例对象
      
    •  await函数不能单独使用
      
  • async/await 让异步代码看起来、表现起来更像同步代码
    async getTableHeader() {
      const { data: res } = await this.$http.get("/data/table/listCloumn", {
        params: {
          userId: this.userId,
          tableName: this.table_info.name,
        },
      })

try,catch

   async loadChannels () {
      try {
        // const { data } = await getUserChannels()
        // this.channels = data.data.channels
        let channels = []

        if (this.user) {
          // 已登录,请求获取用户频道列表
          const { data } = await getUserChannels()
          channels = data.data.channels
        } else {
          // 未登录,判断是否有本地的频道列表数据
          const localChannels = getItem('TOUTIAO_CHANNELS')
          //    有,拿来使用
          if (localChannels) {
            channels = localChannels
          } else {
            //    没有,请求获取默认频道列表
            const { data } = await getUserChannels()
            channels = data.data.channels
          }
        }

        this.channels = channels
      } catch (err) {
        this.$toast('获取频道数据失败')
      }
    },
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kafuka_A

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值