search
HomeWeb Front-endCSS TutorialHow axios makes HTTP request client based on Promise

This time I will show you how axios uses Promise-based HTTP request client. What are the precautions for axios Promise-based HTTP request client? The following is a practical case, let's take a look.

axios


Promise-based HTTP request client, which can be used in the browser and node.js at the same time

Features

Send XMLHttpRequests requests in the browser

Send http requests in node.js

Support PromiseAPI

Intercept requests and responses

Convert requests and Response data

Automatic conversion of JSON data

Client support to protect security from XSRF attacks

Browser support

Installation

Use bower:

$ bower install axios

Using npm:

$ npm install axios

Example

Send a GET request

// Make a request for a user with a given IDaxios.get('/user?ID=12345').then(function(response){console.log(response);}).catch(function(response){console.log(response);});
// Optionally the request above could also be done asaxios.get('/user',{params:{ID:12345}}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});

Send a

POST request

axios.post('/user',{firstName:'Fred',lastName:'Flintstone'}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});

Send multiple concurrent requests


functiongetUserAccount(){returnaxios.get('/user/12345');}functiongetUserPermissions(){returnaxios.get('/user/12345/permissions');}axios.all([getUserAccount(),getUserPermissions()]).then(axios.spread(function(acct,perms){// Both requests are now complete}));

axios API


You can customize the request by passing the corresponding parameters to axios:

axios(config)
// Send a POST requestaxios({method:'post',url:'/user/12345',data:{firstName:'Fred',lastName:'Flintstone'}});
axios(url[, config])
// Sned a GET request (default method)axios('/user/12345');

Request methodAlias

For convenience, we provide aliases for all supported request methods

axios.get(url[, config])
axios.delete(url[, config])
axios.head(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 attributes do not need to be specified in the config parameters.

Concurrency

Helper methods for handling concurrent requests

axios.all(iterable)
axios.spread(callback)

Create an instance

You can create a new axios instance with custom configuration.

axios.create([config])
varinstance=axios.create({baseURL:'https://some-domain.com/api/',timeout:1000,headers:{'X-Custom-Header':'foobar'}});

Instance methods

All available instance methods are listed below, and the specified configuration will be merged with the configuration of the instance.

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

Request configuration

The following are the available request configuration items, only the url is required. If method is not specified, the default request method is GET.

{// `url` is the server URL that will be used for the requesturl:'/user',
// `method` is the request method to be used when making the requestmethod:'get',
// default// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.baseURL:' 
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
// The last function in the array must return a string or an ArrayBuffertransformRequest:[function(data){
// Do whatever you want to transform the datareturndata;}],
// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catchtransformResponse:[function(data){
// Do whatever you want to transform the datareturndata;}],
// `headers` are custom headers to be sentheaders:{'X-Requested-With':'XMLHttpRequest'},
// `params` are the URL parameters to be sent with the requestparams:{ID:12345},
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs,  paramsSerializer:function(params){returnQs.stringify(params,{arrayFormat:'brackets'})},
// `data` is the data to be sent as the request body// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be a string, an ArrayBuffer or a hashdata:{firstName:'Fred'},
// `timeout` specifies the number of milliseconds before the request times out.
// If the request takes longer than `timeout`, the request will be aborted.timeout:1000,
// `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentialswithCredentials:false,
// default// `adapter` allows custom handling of requests which makes testing easier.
// Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)).adapter:function(resolve,reject,config){/* ... */},
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.auth:{username:'janedoe',password:'s00pers3cret'}
// `responseType` indicates the type of data that the server will respond with
// options are 'arraybuffer', 'blob', 'document', 'json', 'text'responseType:'json',
// default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName:'XSRF-TOKEN',
// default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName:'X-XSRF-TOKEN',
// default// `progress` allows handling of progress events for 'POST' and 'PUT uploads'
// as well as 'GET' downloadsprogress:function(progressEvent){
// Do whatever you want with the native progress event}}

Response data structure

The response data includes the following information:

{// `data` is the response that was provided by the serverdata:{},
// `status` is the HTTP status code from the server responsestatus:200,
// `statusText` is the HTTP status message from the server responsestatusText:'OK',
// `headers` the headers that the server responded withheaders:{},
// `config` is the config that was provided to `axios` for the requestconfig:{}}

When using then or catch, you will receive the following response:

axios.get('/user/12345').then(function(response){console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});

Default configuration

You can specify the default configuration for each request.

Global axios default configuration

axios.defaults.baseURL='https:
//api.example.com';axios.defaults.headers.common['Authorization']=AUTH_TOKEN;axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';

Customized instance default configuration

// Set config defaults when creating the instancevarinstance=axios.create({baseURL:' 
// Alter defaults after instance has been createdinstance.defaults.headers.common['Authorization']=AUTH_TOKEN;

Priority order of configuration

Config will be merged with an order of precedence. The order is library defaults found inlib
/defaults.js, thendefaultsproperty of the instance, and finallyconfigargument for the request. The latter will take precedence over the former. Here's an example.
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the libraryvarinstance=axios.create();
// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing outinstance.defaults.timeout=2500;
// Override timeout for this request as it's known to take a long timeinstance.get('/longRequest',{timeout:5000});

Interceptor

You can Intercept requests and responses before processing then or catch

// 添加一个请求拦截器axios.interceptors.request.use(function(config){
// Do something before request is sentreturnconfig;},function(error){
// Do something with request errorreturnPromise.reject(error);});
// 添加一个响应拦截器axios.interceptors.response.use(function(response){
// Do something with response datareturnresponse;},function(error){
// Do something with response errorreturnPromise.reject(error);});

Remove an interceptor:

varmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);

You can add an interceptor to a custom axios instance:

varinstance=axios.create();instance.interceptors.request.use(function(){/*...*/});
错误处理
axios.get('/user/12345').catch(function(response){if(responseinstanceofError){
// Something happened in setting up the request that triggered an Errorconsole.log('Error',response.message);}else{
// The request was made, but the server responded with a status code
// that falls out of the range of 2xxconsole.log(response.data);console.log(response.status);console.log(response.headers);console.log(response.config);}});
Promises
axios 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入polyfill
TypeScript
axios 包含一个TypeScript定义
/// import*asaxiosfrom'axios';axios.get('/user?ID=12345');
Credits
axios is heavily inspired by the$http serviceprovided inAngular. Ultimately axios is an effort to provide a standalone$http-like service for use outside of Angular.
License
MIT

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Related reading:

How VUE uses anmate.css

css gradient color

Easy to use 404 components

How to solve the problem of missing font icons in Iview in the vue-cli shelf

The above is the detailed content of How axios makes HTTP request client based on Promise. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Weekly Platform News: Web Apps in Galaxy Store, Tappable Stories, CSS SubgridWeekly Platform News: Web Apps in Galaxy Store, Tappable Stories, CSS SubgridApr 14, 2025 am 11:20 AM

In this week's roundup: Firefox gains locksmith-like powers, Samsung's Galaxy Store starts supporting Progressive Web Apps, CSS Subgrid is shipping in Firefox

Weekly Platform News: Internet Explorer Mode, Speed Report in Search Console, Restricting Notification PromptsWeekly Platform News: Internet Explorer Mode, Speed Report in Search Console, Restricting Notification PromptsApr 14, 2025 am 11:15 AM

In this week's roundup: Internet Explorer finds its way into Edge, Google Search Console touts a new speed report, and Firefox gives Facebook's notification

The Power (and Fun) of Scope with CSS Custom PropertiesThe Power (and Fun) of Scope with CSS Custom PropertiesApr 14, 2025 am 11:11 AM

You’re probably already at least a little familiar with CSS variables. If not, here’s a two-second overview: they are really called custom properties, you set

We Are ProgrammersWe Are ProgrammersApr 14, 2025 am 11:04 AM

Building websites is programming. Writing HTML and CSS is programming. I am a programmer, and if you're here, reading CSS-Tricks, chances are you're a

How Do You Remove Unused CSS From a Site?How Do You Remove Unused CSS From a Site?Apr 14, 2025 am 10:59 AM

Here's what I'd like you to know upfront: this is a hard problem. If you've landed here because you're hoping to be pointed at a tool you can run that tells

An Introduction to the Picture-in-Picture Web APIAn Introduction to the Picture-in-Picture Web APIApr 14, 2025 am 10:57 AM

Picture-in-Picture made its first appearance on the web in the Safari browser with the release of macOS Sierra in 2016. It made it possible for a user to pop

Ways to Organize and Prepare Images for a Blur-Up Effect Using GatsbyWays to Organize and Prepare Images for a Blur-Up Effect Using GatsbyApr 14, 2025 am 10:56 AM

Gatsby does a great job processing and handling images. For example, it helps you save time with image optimization because you don’t have to manually

Oh Hey, Padding Percentage is Based on the Parent Element's WidthOh Hey, Padding Percentage is Based on the Parent Element's WidthApr 14, 2025 am 10:55 AM

I learned something about percentage-based (%) padding today that I had totally wrong in my head! I always thought that percentage padding was based on the

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools