How 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.
$ bower install axios
$ npm install axios
// 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);});
axios.post('/user',{firstName:'Fred',lastName:'Flintstone'}).then(function(response){console.log(response);}).catch(function(response){console.log(response);});
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(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 methodsaxios.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]])
axios.all(iterable) axios.spread(callback)
axios.create([config]) varinstance=axios.create({baseURL:'https://some-domain.com/api/',timeout:1000,headers:{'X-Custom-Header':'foobar'}});
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]])
{// `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}}
{// `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:{}}
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);});
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';
// Set config defaults when creating the instancevarinstance=axios.create({baseURL:' // Alter defaults after instance has been createdinstance.defaults.headers.common['Authorization']=AUTH_TOKEN;
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});
// 添加一个请求拦截器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);});
varmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



HTTP status code 520 means that the server encountered an unknown error while processing the request and cannot provide more specific information. Used to indicate that an unknown error occurred when the server was processing the request, which may be caused by server configuration problems, network problems, or other unknown reasons. This is usually caused by server configuration issues, network issues, server overload, or coding errors. If you encounter a status code 520 error, it is best to contact the website administrator or technical support team for more information and assistance.

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

Solution: 1. Check the Content-Type in the request header; 2. Check the data format in the request body; 3. Use the appropriate encoding format; 4. Use the appropriate request method; 5. Check the server-side support.

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

The HTTP request times out, and the server often returns the 504GatewayTimeout status code. This status code indicates that when the server executes a request, it still fails to obtain the resources required for the request or complete the processing of the request after a period of time. It is a status code of the 5xx series, which indicates that the server has encountered a temporary problem or overload, resulting in the inability to correctly handle the client's request. In the HTTP protocol, various status codes have specific meanings and uses, and the 504 status code is used to indicate request timeout issues. in customer

How to implement HTTP streaming in C++? Create an SSL stream socket using Boost.Asio and the asiohttps client library. Connect to the server and send an HTTP request. Receive HTTP response headers and print them. Receives the HTTP response body and prints it.
