Axios Study Notes

Source: Internet
Author: User

Official Document Address: Https://github.com/axios/axios

Axios is a Promise-based HTTP library that can be used in browsers and node. js

Characteristics:

? Initiating a xmlhttprequests request from a browser

? Initiating an HTTP request from node. js

? Support Promise API

? Intercept requests and responses

? Transform request and response data

? Cancel Request

? Automatically convert to JSON data

? Client Support Defense XSRF

Supplemental Promise:

Promise is the new asynchronous event handling method in Es6, with the following basic usage:

Let myfirstpromise =NewPromise (Resolve, reject) = {  //automatically call resolve (...) When asynchronous event processing succeeds Method and, if it fails, calls reject (...) .  //In this example, we use the settimeout (...) timer to simulate an asynchronous eventSetTimeout (function() {Resolve ("success!");//at this point, all the code is finished running}, 250);}); Myfirstpromise.then ((successmessage)= {    //Successmessage is the upper resolve (...). The parameters passed in the methodConsole.log ("yay!" +successmessage);});//yay! Success!

The Promise object is a constructor that takes a function as a parameter, and the two parameters of the function are resolve (literally: Resolve) and reject (literally: reject), which are two functions that are provided by the JS engine without deploying itself.

The purpose of the Resolve function is to change the state of the Promise object from "unfinished" to "successful", to invoke when the asynchronous operation succeeds, and to pass the result of the asynchronous operation as a parameter.

The purpose of the Reject function is to change the state of the Promise object from "incomplete" to "failed", to invoke when an asynchronous operation fails, and to pass the error reported by the asynchronous operation as a parameter.

In the above example, Myfirstpromise is an instance of Promise object creation, and after the Promise instance is generated, you can specify the callback function for the resolve state and the reject State, respectively, with the then method, which is optional and does not necessarily provide

Getjson ('/posts.json '). Then (function(posts) {  //  ...}). Catch Errorconsole.log (' Error ')  {///  handling Getjson and the previous callback function run  ', error);});

In the above code, the Getjson method returns a Promise object that, if the object's State becomes resolved, invokes the callback function specified by the then method, and if an asynchronous operation throws an exception, the state becomes rejected, and the callback function specified by the Catch method is called. Handle this error. In addition, the then method specifies a callback function that is caught by the catch method if an error is thrown in the run

Installation:

// command Line Input npm Install Axios // introduction of Axiosimport Axios from ' Axios '

Examples available on the website:

Perform a GET request

 //  user initiated request for the given ID  axios.get ('/user? id=12345 '  function   (response) {Console.log (response); })  . catch   (function   (Error) {Console.log (error); }); //  The above request can also be done  axios.get ('/user ' 12345}}). Then ( function   (response) {Console.log (response); })  . catch   (function   (Error) {Console.log (error); });

Perform a POST request

Axios.post ('/user ', {    ' Fred ',    ' Flintstone '  })  . Then (function  (response) {    Console.log (response);  })  . Catch (function  (error) {    console.log (error);  });

Executing multiple concurrent Requests

function Getuseraccount () {  return axios.get ('/user/12345 ');} function getuserpermissions () {  return axios.get ('/user/12345/permissions ');} Axios.all ([Getuseraccount (), Getuserpermissions ()])  . Then (axios.spread (function  (ACCT, perms) {    //  two requests completed  });

Now follow the official website example to operate under:

Demo 1: Successful launch of a GET request

 <  button  type  = "button"   class  = "btn btn-primary"   @click  = "Get"  >  get</ button  >  
Import Axios from ' Axios ';     default {        methods: {            get () {                axios.get ('.. /.. /.. /static/data/sidenav.json '). Then (response=>console.log (response))                                        . Catch (error=>Console.log (Error))     }}}

Operation Result:

Demo 2: Failed to initiate GET request, according to the above example, access a nonexistent hello.txt file

Import Axios from ' Axios ';     default {        methods: {            get () {                axios.get ('./hello.txt '). Then (response=>console.log (response))                                       . Catch (Error=>console.log (' Error message: ' + error)}     }}}}

Operation Result:

Axios API

You can create requests by passing related configurations to Axios

Axios (config)//send a POST requestAxios ({method:' Post ', URL:'/user/12345 ', data: {firstName:' Fred ', LastName:' Flintstone '  }});//get a GET request from a remote pictureAxios ({method:' Get ', URL:' Http://bit.ly/2mTM3nY ', Responsetype:' Stream '}). Then (function(response) {Response.data.pipe (Fs.createwritestream (' Ada_lovelace.jpg ') }); Axios (url[, config] )//Send a GET request (default method)Axios ('/user/12345 ');

Alias of the Request method:

For convenience, all supported request methods provide aliases

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])

Note: When using the Alias method, the URL, method, and data properties do not have to be specified in the configuration

Axios Study Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.