axios sends a request, one is done

1. How axios sends requests

Shorthand:

The delete request is similar to the get request, and the put request is similar to the post request.

// 为给定 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);
  });
Simplified:
// 发送 POST 请求
axios({
    
    
  method: 'post',
  url: '/user/12345',
  data: {
    
    
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

There is no problem with complicated writing, how to configure the official document is very clear;
but the abbreviated configuration is not very comprehensive;

Shorthand configuration (carrying request headers and parameters):

Summary: If a get request is requested, a parameter configuration will be performed after imitating a traditional request. But if it is a post request, it is all objects, and then write a key-value pair in the object

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. Process the data obtained by axios sending the request

== .then .catch used in the above example==

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

async 和await

  • async is placed in front of the function as a keyword
    • Any async function will implicitly return a promise
  • The await keyword can only be used in functions defined using async
    • await后面可以直接跟一个 Promise实例对象
      
    •  await函数不能单独使用
      
  • async/await makes asynchronous code look and behave more like synchronous code
    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('获取频道数据失败')
      }
    },

Guess you like

Origin blog.csdn.net/weixin_43131046/article/details/114283481