axios怎样基于Promise的HTTP请求客户端
这次给大家带来axios怎样基于Promise的HTTP请求客户端,axios基于Promise的HTTP请求客户端的注意事项有哪些,下面就是实战案例,一起来看一下。
axios
基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用
功能特性
在浏览器中发送XMLHttpRequests请求
在 node.js 中发送http请求
支持PromiseAPI
拦截请求和响应
转换请求和响应数据
自动转换 JSON 数据
客户端支持保护安全免受XSRF攻击
浏览器支持
安装
使用 bower:
$ bower install axios
使用 npm:
$ npm install axios
例子
发送一个GET请求
// 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);});
发送一个POST请求
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 API
可以通过给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');
请求方法别名
为方便起见,我们为所有支持的请求方法都提供了别名
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、method和data属性不需要在 config 参数里面指定。
并发
处理并发请求的帮助方法
axios.all(iterable) axios.spread(callback)
创建一个实例
你可以用自定义配置创建一个新的 axios 实例。
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是必需的。如果没有指定method,默认的请求方法是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}}
响应的数据结构
响应的数据包括下面的信息:
{// `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:{}}
当使用then或者catch时, 你会收到下面的响应:
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 默认配置
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});
拦截器
你可以在处理then或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);});
移除一个拦截器:
varmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);
你可以给一个自定义的 axios 实例添加拦截器:
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
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:
以上是axios怎样基于Promise的HTTP请求客户端的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

http状态码520是指服务器在处理请求时遇到了一个未知的错误,无法提供更具体的信息。用于表示服务器在处理请求时发生了一个未知的错误,可能是由于服务器配置问题、网络问题或其他未知原因导致的。通常是由服务器配置问题、网络问题、服务器过载或代码错误等原因导致的。如果遇到状态码520错误,最好联系网站管理员或技术支持团队以获取更多的信息和帮助。

掌握HTTP301状态码的含义:网页重定向的常见应用场景随着互联网的迅猛发展,人们对网页交互的要求也越来越高。在网页设计领域,网页重定向是一种常见且重要的技术,通过HTTP301状态码来实现。本文将探讨HTTP301状态码的含义以及在网页重定向中的常见应用场景。HTTP301状态码是指永久重定向(PermanentRedirect)。当服务器接收到客户端发

在日常生活中,我们常常会遇到承诺与兑现之间的问题。无论是在个人关系中,还是在商业交易中,承诺的兑现都是建立信任的关键。然而,承诺的利与弊也常常会引起争议。本文将探讨承诺的利与弊,并给出一些建议,如何做到言出必行。承诺的利是显而易见的。首先,承诺可以建立信任。当一个人信守承诺时,他会让别人相信自己是一个可信赖的人。信任是人与人之间建立起的纽带,它可以让人们更加

解决方法:1、检查请求头中的Content-Type;2、检查请求体中的数据格式;3、使用适当的编码格式;4、使用适当的请求方法;5、检查服务器端的支持情况。

HTTP状态码200:探索成功响应的含义与用途HTTP状态码是用来表示服务器响应状态的数字代码。其中,状态码200表示请求已成功被服务器处理。本文将探索HTTP状态码200的具体含义与用途。首先,让我们了解一下HTTP状态码的分类。状态码被分为五个类别,分别是1xx、2xx、3xx、4xx和5xx。其中,2xx表示成功的响应。而200是2xx中最常见的状态码

Promise.resolve()详解,需要具体代码示例Promise是JavaScript中一种用于处理异步操作的机制。在实际开发中,经常需要处理一些需要按顺序执行的异步任务,而Promise.resolve()方法就是用来返回一个已经Fulfilled状态的Promise对象。Promise.resolve()是Promise类的一个静态方法,它接受一个

HTTP请求超时,服务器端常常会返回504GatewayTimeout状态码。该状态码表示服务器在执行某个请求时,经过一段时间后仍未能获取到请求所需的资源或完成请求的处理。它是5xx系列的状态码,表示服务器端遇到了临时的问题或过载,导致无法正确处理客户端的请求。在HTTP协议中,各种状态码都有特定的含义和用途,而504状态码则用于表示请求超时问题。在客户

如何在C++中实现HTTP流传输?使用Boost.Asio和asiohttps客户端库创建SSL流套接字。连接到服务器并发送HTTP请求。接收HTTP响应头并打印它们。接收HTTP响应正文并打印它。
