This article guides axios beginners out of the smog in the detailed introduction and basic use of axios (1)

Table of contents

Introduction to axios

Introduction of axios

Basic use of get and post requests in axios


Introduction to axios

        I believe that as a front-end player, it is absolutely necessary to send http network requests. At this time, we will use an API provided by the browser, which is Ajax. However, the use of Ajax requires us to create a new XML (minion) instance through the XMLHttpRequest constructor each time, then prepare the request body and send the http request, and finally monitor the state through XHR's onreadystatechange and get the returned data . And it is also necessary to perform a series of processing on the returned data, such as converting to the type of JS object, and there is still a series of asynchronous processing. If Ajax is used in multiple places, the amount of code is very complicated and maintenance is also very difficult. Just like we use native JS for development, scalability and maintainability are not guaranteed, teamwork is difficult, and development efficiency is low. In this case, our front-end native JS has a framework developed for us by our predecessors, then Ajax also has its own framework --- Axios.

       Axios is a promise-based network request library for browsers and node.js. Because Ajax requests are asynchronous, its encapsulation is implemented based on promise, an api specially designed to handle asynchronous processing. So in the subsequent data reception, we usually operate in .then.

Axios has the following features:

        1. Create XMLHttpRequests from the browser  . Axios has created a new instance object for us in the package for subsequent use. We don't care about the creation of axios during use.

        2. Creating  an http  request from node.js allows us to use it directly in the node environment.

        3. Promise  API is supported  , because axios is an encapsulation operation based on promise, so we don't need to care too much about synchronization and asynchrony in subsequent use.

        4. Intercept requests and responses . Axios provides us with a powerful request and response interception API, which allows us to define our own logical operations before sending requests and returning data.

        5. To transform request and response data , through apis such as transformRequest and transformResponseapi provided by axios, the data body can be transformed arbitrarily during sending and responding.

        6. Cancel the request , use the cancelToken API to cancel the request sent last time, usually to deal with the situation where the user sends the request frantically, similar to throttling, the next request will not be allowed until the server responds to the data.

        7. Automatically convert JSON data . The data returned by axios is directly of JS object type, so we don’t need to use JSON.parse’s string-to-object method.

        8. The client supports defense against XSRF


Introduction of axios

If you use axios with html files, you can introduce them through the following code.

<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.min.js"></script>

If it is used in the project, it can be installed directly by npm install axios.


Basic use of get and post requests in axios

The same is a get request, which can be implemented in two ways in axios.

1. Realized by calling the get function, the parameter here can be a string of characters spliced ​​behind the url path, or a configuration object {params:{parameter name: value}} can be passed in

axios.get('http://localhost:3000/user?ID=12345')
  .then((response) => {
    // 处理成功情况
    console.log(response);
  })
  .catch((error) =>  {
    // 处理错误情况
    console.log(error);
  })

// 如果不写.get的话,默认是get请求
axios('/user,{params:{ID: 12345}}).then((response) => {})

2. By directly calling the implementation of axios, a configuration object is passed in here.

axios({
	method: "GET",
	url: "http://localhost:3000/user?ID=12345",
    // 或者
    // url: "http://localhost:3000/user",
    // {params:{ID:12345}}
}).then((response) => {
    // 处理成功情况
    console.log(response);
  })
  .catch((error) =>  {
    // 处理错误情况
    console.log(error);
  })

Axios also supports async/await writing 

async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Post requests are usually used to submit data to the server, let's see how it is written:

axios({ // 发送AJAX请求
	// 请求类型
	method: "POST",
	// 需要提交数据的URL路径
	url: "http://localhost:3000/posts",
	// 设置发送的数据体(新增内容)
	data: {
	    title: "已经步入深秋了,树叶渐渐的开始下落了!",
	    author: "不读诗意",
    }
}).then((response) => {
    console.log(response);
})
.catch((error) => {
    console.log(error);
})

 There is also a series of in-depth study of axios in the topic, I hope it can be helpful!

Guess you like

Origin blog.csdn.net/weixin_60678263/article/details/128176235