One 、 What is? axios ?

axios Is based on Promise Of ajax Packaging Library , It is also the most popular front-end at present ajax Request Library . Simply put, send get、post request , It's a lightweight Library , When in use, you can directly introduce .

Two 、axios Characteristics

  1. Asynchronous ajax Request Library .
  2. On the browser side and node End can be used .
  3. Support Promise API.
  4. Support request and response interception .
  5. Automatic conversion of response data JSON data .
  6. Support request cancellation .
  7. Multiple requests can be sent in batches .
  8. The client supports security protection , Free from XSRF attack .

3、 ... and 、axios API

3.1、 install

/* npm install */
npm install axios --save /* bower install */
bower install axios /* Use yarn */
yarn add axios /* cdn introduce */
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

notes : If a simple static page uses , Suggest cdn Mode introduction .

3.2、axios API

towards axios Transmission related configuration parameters , Create request . Such as :axios(config)

/* If you send a post The requested configuration parameters are as follows */
axios({
method: 'post', // Request method
url: '/user/12345', // Access interface
data: { // To transmit data
firstName: 'Fred',
lastName: 'Flintstone'
}
});
/* If you send a get The requested configuration parameters are as follows */
axios({
method: 'get',
url: 'http://localhost:80/one',// Request interface
responseType: 'stream'// Response form
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('save.jpg')) // Save the picture
});

3.3、axios Request method

above axios API Every time a request is made , You need to set its request method, response header timeout and other information , It is cumbersome to use , For convenience ,axios Aliases are provided for all supported request methods , The request can be initiated directly in a specified way , Other parameters can be set globally . Such as :

axios('/user/id=1');

Above axios Send the request directly , When the request mode is not set , By default get request , And ajax and fetch identical . So it's a get request , You can also use get Method to send , The following example :

axios.get(
'1.txt' ,
{
params:{id:'1'}
}
).then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})

It can be written in brief. axios(url,config).

Other specific methods are :

axios.request(config)
axios.get( url , config)
axios.delete( url , config)
axios.head( url , config)
axios.options( url , config)
axios.post( url [,data [, config ]])
axios.put( url [,data [, config ]])
axios.patch( url [,data [, config ]])

3.4、 Send requests in bulk

Multiple network requests are often executed concurrently in network requests , Sometimes we need to deal with their returned results in a unified way , therefore axios Concurrent processing .axios.all() Multiple network requests can be sent in parallel , Wait until all requests return , To continue processing .

Use the syntax :

/* The first way to deal with it */
axios.all([
axios.get(URL1),
axios.get(URL2),
]).then(res=>{
console.log(res) // Back to res Is an array ,res[0] Is the first request data res[1] Is the second request data
}) /* The second way to deal with it */
axios.all([
axios.get(URL1),
axios.get(URL2),
]).then(
axios.spread((res1,res2)=>{
res1 // Is the first request to return data
res2 // Is the second request to return data
})
)

Use axios.spread Can automatically split request return data .

1.5、 Global default configuration

The global default configuration is mainly used for each request . Save time typing code , When you want to modify , Just change one and you can change it all .

Common global default configurations are :

axios.defaults.baseURL = "http://localhost:8080/" // Configure the domain name 
axios.defaults.timeout = 6000; // In milliseconds , Set timeout /* Head set */
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

3.6、axios example

// Configure default parameters when instantiating 
const instance = axios.create({
baseURL: 'https://api.example.com'
}); // Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN

Why axios Instantiation , Because global instantiation http The request has a global response interception , When some of our interfaces cannot return status codes , We will not get response, At this point, we need to be in the current api Re instantiate a axios, Set a new response intercept code .

3.7、 Interceptor

The interceptor is divided into two , There are request interception and response interception , Some businesses can be handled uniformly .

  • Request interceptor :
/*
Request interceptor
Uniformly add... Before sending the request token
*/
axios.interceptors.request.use(config=>{
config.headers.token = sessionStorage.getItem("token") // add to toke
return config
},err=>{
console.log(err)// Request error
})
  • Response interceptors
axios.interceptors.response.use(response=>{
return response
},err=>{
console.log(err)// Response error
})

3.8、 Response content

Basically in use , The first instance request succeeded , Print the results console.log(res) . The results are as follows :

{
data:{},
status:200,
// Returned from the server http Status text
statusText:'OK',
// Response header information
headers: {},
//config Some configuration information at the time of request
config: {}
}

Four 、axios Common applications

axios It can be used on the browser side , It can also be in node.js Use in . What is sent on the browser side is XMLHttpRequest, stay node.js Send the http . image VUE、React、Node And other projects can use axios.

Front end and back end data interaction ( 5、 ... and )—— What is? axios? More articles about

  1. Yes GraphQL-BFF: Research on the front end and back end data interaction scheme under the background of microservice ------- quote

    With multiple terminals . Multi platform . Multiple business forms . Multi technology selection and other aspects of development , The data interaction between the front end and the back end , Increasingly complex . The same data , It may be in many different forms and structures , Consumed in a variety of scenarios . In an ideal situation , All of this complexity can be borne by the back end . Front end only ...

  2. There are two ways to do this asp.net The front and back data interaction of the scheme (aspx file 、html+ashx+ajax)

    One HTML The page can only display HTML Code information , Can't interact with database .asp.net The scheme provides the method of interaction between web page and database , Here are two :①aspx file ②ashx file +ajax technology One . Create database Here we use ...

  3. vue-resource Use , Front end and back end data interaction

    vue-resource Use , Front end and back end data interaction 1: Import vue And vue-resource Of js js download :   https://pan.baidu.com/s/1fs5QaNwcl2AMEyp_kUg ...

  4. The interactive processing of front-end and back-end data is based on native JS Template engine development

    json Data error handling , hold json Copy file data to ----> https://www.bejson.com/ Online resolution json It's intuitive to see if it's json Wrong data , At the console break point , There's a mistake, there's a mistake ...

  5. web Front end and back end data interaction

    Front end and back-end data interaction is every web The process a programmer must be familiar with , The data interaction between the front end and the back end focuses on how the front end obtains the data returned by the back end , After all, the back end usually only needs to encapsulate the data into a jsonMap, then return It's over . Let's go through a li ...

  6. Front and back end data interaction tools --Protobuf

    Protobuf Introduce Protocol Buffers( also called protobuf) yes Google Language neutrality . Platform neutrality . Extensible and structured data serialization mechanism . https://github.com/prot ...

  7. Vue Small project second hand book Mall :( Two )axios Front end and back end data interaction

    Implementation content : Write routing interface (express) axios Take the data One . Write the interface 1. We need to get the data from the front end to the back end ( Previously written data.json) It can be used vue-resourse Or use axios, stay vue2 And then the authorities ...

  8. SpringMVC Summary of front and back end data interaction

    controller As controller , The general function is as V The data of the terminal is received and delivered to M Layer to deal with , And then manage V The jump .SpringMVC That's what it's all about , It is mainly divided into : Receive the value of the form or request , Define filters , Jump to the page : In fact, that is ser ...

  9. Spring MVC Summary of front and back end data interaction

    controller As controller , The general function is as V The data of the terminal is received and delivered to M Layer to deal with , And then manage V The jump .SpringMVC That's what it's all about , It is mainly divided into : Receive the value of the form or request , Define filters , Jump to the page : In fact, that is ser ...

  10. day67 Front end and back end data interaction

    Catalog One . The encoding format of the data transmitted from the front end to the back end (contentType) 1 form Forms 2 ajax request Two .ajax send out json Format data 3、 ... and .ajax Send a file Four .django The built-in serialization component (drf Do matting ...

Random recommendation

  1. C++ Why should a destructor be a virtual function

    notes : The content of this paper comes from zhice163 post , Thanks for the author's arrangement . . Why is the destructor of the base class a virtual function ? When implementing polymorphism , When a derived class is operated with a base class , When destruct, prevent only the base class and not the derived class . The following is transferred from the network : source address h ...

  2. Hadoop Pseudo distribution mode configuration deployment

    . Description of experimental environment Be careful : This experiment needs to continue to operate according to the single machine mode deployment in the previous section 1. Environment login Automatic login without password , System user name shiyanlou, password shiyanlou 2. Introduction to the environment In this experiment, the experimental environment is the one with desktop ...

  3. istio introduction (01)istio What is it? ?

  4. Cattle from PAT Class B (Basic Level) The real question - Digital classification (20)

    Title Description Given a series of positive integers , Please classify the numbers as required , And output the following 5 A digital : A1 = Can be 5 The sum of all even numbers in a divisible number : A2 = Will be 5 Except after 1 The numbers of are interleaved and summed in the given order , Computation n1-n2+n3-n4 ...

  5. java note ----JVM Memory

    The runtime data area includes : Virtual machine stack area , Heap area , Method area , Native Method Stack , Program counter Virtual machine stack area  : That's what we call the stack area , Thread private , Basic storage type , References to objects and  returnAddress , Complete allocation during compilation . Heap area   ...

  6. Pnel Control

    Group class control Panel controls (Panel) Group box control (GroupBox) Tab controls (TabControl) Other controls   Panel Control is created by System.Windows.Forms.Panel Class provides the , The main ...

  7. python list list

    1. What is a list List is a variable data type List by [] To express , Each element is separated by commas . A list can hold anything . Objects that can hold objects . A list can hold a lot of data 2. Index and slice the list The list is the same as the string . There are also indexes ...

  8. Sql Server char、varchar、nchar、nvarchar The difference between

    (1) Definition : char: Fixed length , Storage ANSI character , Fill in the blanks . nchar: Fixed length , Storage Unicode character , Fill in the blanks varchar: Variable length , Storage ANSI character , according to ...

  9. ThreadPoolExecutor( Part 1 )

    Java There are two thread pool classes :ThreadPoolExecutor and ScheduledThreadPoolExecutor, Inherit AbstractExecutorService class ,AbstractExecut ...

  10. 【 Installation key 】webStorm-201703 edition

    On the activation page, select License Server, Input :http://idea.codebeta.cn, Click on Activate Activate .