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);}});Promisesaxios 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入polyfillTypeScriptaxios 包含一个TypeScript定义/// import*asaxiosfrom'axios';axios.get('/user?ID=12345');Creditsaxios 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.LicenseMIT

相信看了本文案例你已经掌握了方法,更多精彩请关注创想鸟其它相关文章!

相关阅读:

VUE如何使用anmate.css

css的渐变颜色

好用的404组件

解决Iview在vue-cli架子中字体图标丢失的方法

以上就是axios怎样基于Promise的HTTP请求客户端的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1609071.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月24日 00:34:33
下一篇 2025年12月24日 00:34:52

相关推荐

  • HTML如何调用API接口_异步数据获取方法【指南】

    必须借助JavaScript发起异步请求调用API,方法包括:一、fetch API;二、XMLHttpRequest;三、async/await封装fetch;四、JSONP跨域;五、Axios库。 如果您在HTML页面中需要从服务器获取动态数据,但页面无法直接执行后端逻辑,则必须借助JavaSc…

    2025年12月23日
    000
  • html如何写java代码_在HTML中嵌入Java代码方法【嵌入】

    现代浏览器无法直接运行Java代码,需通过服务端技术(如JSP、Thymeleaf)嵌入执行,或采用前后端分离模式由Java后端提供API供HTML通过AJAX调用。 如果您希望在HTML页面中直接运行Java代码,需注意现代浏览器已不再支持通过applet>标签或JavaScript调用Ja…

    2025年12月23日
    000
  • Vue.js动态图片源不更新?深入理解响应式与缓存问题

    本文深入探讨vue.js中动态图片src无法响应式更新的常见原因及解决方案。我们将分析方法调用在模板中的非响应式特性、浏览器缓存机制,并提供两种核心策略:通过setinterval周期性更新依赖数据以触发响应式变化,以及通过url查询参数实现缓存失效。最终,强调将逻辑封装到计算属性中的最佳实践,以构…

    2025年12月23日
    000
  • 如何通过编程向Discord Webhook发送当前URL链接

    本教程详细介绍了如何利用编程方式将当前url链接发送至discord webhook。文章涵盖了理解discord webhook消息体格式、选择合适的http客户端库、构建包含url的json数据包(payload),以及通过post请求将其发送出去的关键步骤,并提供了python语言结合http…

    2025年12月23日
    000
  • Vue.js 动态图片 src 不响应式更新:原理与解决方案

    本文深入探讨了vue.js中动态图片`src`不响应式更新的常见问题,尤其是在基于时间或其他外部因素切换图片场景下的原因。文章分析了直接在模板中使用方法作为条件和依赖的局限性,并提供了两种主要解决方案:一是通过添加时间戳进行缓存失效,二是利用`setinterval`定期更新响应式数据结合计算属性来…

    2025年12月23日
    000
  • Vue.js动态图片src响应性问题深度解析与解决方案

    本文深入探讨vue.js中动态图片`src`不具备响应性更新的常见原因及解决方案。主要分析了浏览器缓存机制对图片更新的影响,以及vue.js组件中方法调用与计算属性响应性之间的差异。文章提供了通过时间戳进行缓存失效、利用`setinterval`更新响应式数据,并结合计算属性优化动态图片路径生成的实…

    2025年12月23日
    000
  • Vue.js中动态图片src不响应式更新的排查与解决方案

    Vue.js应用中,当图片`src`需要根据时间或其他动态条件响应式更新时,开发者常遇到图片不自动刷新的问题。本文将深入分析导致此问题的常见原因,特别是模板中方法调用的非响应性,并提供基于计算属性、定时器更新状态的优化策略,以及如何通过URL参数处理浏览器缓存,确保图片内容能够按预期动态展示,提升用…

    2025年12月23日
    000
  • React中基于用户输入动态过滤列表元素的实践指南

    本教程详细介绍了如何在react应用中实现基于用户输入的动态列表过滤功能。通过利用react的状态管理机制,我们将演示如何实时响应用户输入,对数据列表进行筛选,并高效地渲染过滤后的结果,从而提升用户体验,特别适用于聊天用户列表、商品目录等场景。 在现代Web应用开发中,动态过滤列表是提升用户体验的关…

    2025年12月23日
    000
  • Vue.js 动态表单:实现下拉框与文本框的智能切换

    本文将详细介绍如何在 Vue.js 应用中实现一个常见的动态表单需求:当用户在下拉选择框中选中“其他”选项时,自动将其转换为一个可供输入的文本框。我们将利用 Vue 的条件渲染指令 v-if 和 v-else,结合 vue-multiselect 组件,构建一个功能完善且用户体验良好的解决方案,并探…

    2025年12月23日
    000
  • vue里html页面怎么运行_vue中运行html页面方法【教程】

    可通过iframe嵌入HTML页面,将文件置于public目录并用src引用;2. 使用fetch获取HTML内容结合v-html渲染,注意防范XSS;3. 借助raw-loader等工具在构建时导入HTML字符串;4. 结合Vue Router按需加载静态页面内容。 如果您在Vue项目中需要运行或…

    2025年12月23日
    000
  • 在React和JavaScript应用中提交表单时保持URL整洁的策略

    提交html表单时,默认的get方法会将表单数据附加到url中,导致url冗长且暴露数据。为避免此问题,应使用post方法,它将数据封装在http请求体中发送,从而保持url路径的简洁和数据隐私。 理解表单数据在URL中出现的原因 当我们在网页中使用HTML 以上就是在React和JavaScrip…

    2025年12月23日
    000
  • React/JavaScript表单提交:保持URL整洁的实践指南

    本文旨在解决web表单提交后url中出现表单字段参数的问题。当表单使用默认的get方法提交时,数据会被附加到url。通过将表单的提交方法明确设置为post,可以将表单数据封装在http请求体中发送,从而确保url保持简洁,不暴露任何查询参数。 理解表单提交与URL参数 当我们在网页中使用HTML 以…

    2025年12月23日
    000
  • React组件中基于用户输入动态筛选列表元素教程

    本教程旨在详细讲解如何在React应用中实现基于用户输入动态筛选列表元素的功能。我们将通过状态管理、事件处理和条件渲染等React核心概念,构建一个实用的用户列表搜索过滤组件,确保列表内容能够根据用户的实时输入进行高效、流畅的更新与展示。 在现代Web应用中,用户经常需要从大量数据中快速定位特定信息…

    2025年12月23日
    000
  • React组件复用与数据传递深度指南

    本文深入探讨react中组件复用和数据传递的多种策略。从基础的props传递到高级的context api和状态管理库,我们将详细阐述如何构建可复用的ui组件,并高效地在不同组件间共享数据,以减少代码冗余并提升应用的可维护性与可扩展性。 在现代前端开发中,尤其是在使用React等组件化框架时,构建可…

    2025年12月23日
    000
  • Svelte中的函数优化:为何你不再需要useCallback

    svelte的编译时优化与react的运行时渲染机制截然不同。在react中,`usecallback`用于记忆化函数以避免不必要的重渲染计算;而svelte作为编译器,能够精准识别并更新受影响的dom部分。因此,svelte开发者无需手动记忆化函数,其独特的响应式系统已在编译阶段高效处理了性能优化…

    2025年12月23日
    000
  • 深入理解Svelte的响应式机制:为何无需useCallback

    svelte作为一款编译器,其独特的响应式系统与react的运行时机制截然不同。本文将深入探讨react中`usecallback`钩子的作用及其在svelte中为何不再必要,帮助开发者理解svelte如何通过编译时优化实现高效的dom更新,从而简化代码并提升开发体验。 React中useCallb…

    2025年12月23日
    000
  • Svelte中无需useCallback:理解其与React的差异

    svelte作为编译器,其组件更新机制与react的虚拟dom渲染方式截然不同。react依赖usecallback等hook优化函数引用以避免不必要的重渲染,而svelte通过编译时分析精确更新受影响的dom,因此在svelte中通常无需使用usecallback来优化性能。 在现代前端开发中,R…

    2025年12月23日
    000
  • JavaScript结合SWAPI实现用户输入搜索:API请求构建与调试指南

    本教程旨在解决使用javascript和swapi时,因api请求url构建不当导致的404错误。文章将详细指导如何正确处理用户输入,构建符合swapi规范的搜索url,并提供最佳实践,包括查阅api文档和独立测试api接口,以确保前端应用能准确获取并展示数据。 在现代Web开发中,通过API获取数…

    2025年12月23日
    000
  • 如何使用JavaScript和Axios正确调用SWAPI进行搜索查询

    本教程旨在解决使用javascript和axios调用swapi时常见的api url构造错误。文章将详细阐述swapi搜索接口的正确用法,包括如何构建带有资源类型和搜索参数的url,并提供完整的代码示例和最佳实践,帮助开发者高效地从swapi获取数据并展示在网页上。 理解SWAPI搜索接口的正确用…

    2025年12月23日
    000
  • Svelte组件中的函数优化:为何无需useCallback

    在svelte中,由于其独特的编译时优化和细粒度的响应式系统,开发者通常无需像react那样使用`usecallback`等hook来优化函数的引用相等性。svelte编译器能够智能地处理组件内部的函数定义,确保在状态更新时只进行必要的dom操作,从而避免了不必要的函数重新创建或子组件重新渲染,简化…

    2025年12月23日
    000

发表回复

登录后才能评论
关注微信