Vue中发送ajax请求——axios使用详解

时间:2021-12-31 19:47:00

axios

基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用

功能特性

  • 在浏览器中发送 XMLHttpRequests 请求
  • 在 node.js 中发送 http请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 自动转换 JSON 数据
  • 客户端支持保护安全免受 XSRF 攻击

浏览器支持

Vue中发送ajax请求——axios使用详解

安装

使用 bower:

$ bower install axios

使用 npm:

$ npm install axios

例子

发送一个 GET 请求

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
// Optionally the request above could also be done as
axios.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);
});

发送多个并发请求

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) {
// Both requests are now complete
}));

axios API

可以通过给 axios传递对应的参数来定制请求:

axios(config)
// Send a POST request
axios(
{
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])
var instance = 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 request
url:'/user',
// `method` is the request method to be used when making the request
method: '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: 'https://some-domain.com/api/',
// `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 ArrayBuffer
transformRequest: [function (data) {
// Do whatever you want to transform the data return data;
}],
// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catch
transformResponse: [function (data) {
// Do whatever you want to transform the data return data;
}],
// `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` are the URL parameters to be sent with the request
params: { ID: 12345 };
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.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 hash
data: { 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 credentials
withCredentials: 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 token
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `progress` allows handling of progress events for 'POST' and 'PUT uploads' as well as 'GET' downloads
progress: function(progressEvent) {
// Do whatever you want with the native progress event
}
}

响应的数据结构

响应的数据包括下面的信息:

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

当使用 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 instance
var instance = axios.create({baseURL: 'https://api.example.com'});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置的优先顺序

Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument 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 library
var instance = axios.create();
// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;
// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {timeout: 5000});

拦截器

你可以在处理 then 或 catch 之前拦截请求和响应

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

移除一个拦截器:

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

你可以给一个自定义的 axios 实例添加拦截器:

var instance = axios.create();
instance.interceptors.request.use(function () {
/*...*/
});

错误处理

axios.get('/user/12345').catch(function (response) {
if (response instanceof Error) {
// Something happened in setting up the request that triggered an Error
console.log('Error', response.message);
} else {
// The request was made, but the server responded with a status code
// that falls out of the range of 2xx
console.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 定义

/// <reference path="axios.d.ts" />
import * as axios from 'axios';
axios.get('/user?ID=12345');

Credits

axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular.

License

MIT

转载:https://www.awesomes.cn/repo/mzabriskie/axios

Vue中发送ajax请求——axios使用详解的更多相关文章

  1. Vue 中使用Ajax请求

    Vue 项目中常用的 2 个 ajax 库 (一)vue-resource vue 插件, 非官方库,vue1.x 使用广泛 vue-resource 的使用 在线文档   https://githu ...

  2. rails中发送ajax请求

    最近在写一个blog系统练练手,遇到一个一个问题,用户添加评论的时候想发送ajax请求,但是rails里的ajax和Python中的不太一样,Python中的ajax是用js,jquery实现的和ra ...

  3. python接口自动化(六)--发送get请求接口(详解)

    简介 如果想用python做接口测试,我们首先有不得不了解和学习的模块.它就是第三方模块:Requests. 虽然Python内置的urllib模块,用于访问网络资源.但是,它用起来比较麻烦,而且,缺 ...

  4. vue中 localStorage的使用方法(详解)

    vue中实现本地储存的方法:localStorage,在HTML5中,新加入了一个localStorage特性,这个特性主要是用来作为本地存储来使用的,解决了cookie存储空间不足的问题(cooki ...

  5. Spring Boot之发送HTTP请求(RestTemplate详解)

    原文作者:微笑面对生活 https://www.javazhiyin.com/19714.html#comment-345 RestTemplate是Spring提供的用于访问Rest服务的客户端,R ...

  6. Vue中ESlint配置文件eslintrc&period;js文件详解

    最近在跟着视频敲项目时,代码提示出现很多奇奇怪怪的错误提示,百度了一下是eslintrc.js文件没有配置相关命令,ESlint的语法检测真的令人抓狂,现在总结一下这些命令的解释,方便以后查阅. 默认 ...

  7. vue中v-model动态生成的实例详解

    每一行有一个input和一个select,其中行数是根据服务器返回的json数据动态变化的.那么问题来了,我们要怎样动态生成v-model? <template> <div> ...

  8. vue中&dollar;refs的用法及作用详解

    一般来讲,获取DOM元素,需要使用document.querySelector('#input1')方法去获取dom节点,然后再获取input1的值. 但是使用了ref绑定之后,我们就不需要再获取do ...

  9. Vue中使用axios发送ajax请求

    作为前后端交互的重要技巧--发送ajax请求,在Vue中我们使用axio来完成这一需求: 首先是下载axios的依赖, npm install --save axios vue-axios 然后在ma ...

随机推荐

  1. Hadoop2&period;x源码-编译剖析

    1.概述 最近,有小伙伴涉及到源码编译.然而,在编译期间也是遇到各种坑,在求助于搜索引擎,技术博客,也是难以解决自身所遇到的问题.笔者在被询问多次的情况下,今天打算为大家来写一篇文章来剖析下编译的细节 ...

  2. 关于VS2010&OpenCurlyDoubleQuote;ADO&period;NET Entity Data Model模板丢失或者添加失败问题

    我最近在安装vs2010后,添加ADO.NET Entity 实体时发现,我的新建项里面并没有这个实体模型,后来我就在博问里面发表了问题,请求大家帮忙解决,悲剧的是少有人回应啊,呵呵,不过我还是在网上 ...

  3. php 修改 AppServ 下Apache 端口

    php 修改 AppServ 下Apache 端口 步骤一:把 C:\AppServ\Apache2.2\conf 中httpd.conf修改了 还不正确 步骤二:把httpd.conf  中List ...

  4. c&num; 如何处理自定义消息

    C#自定义消息通信往往采用事件驱动的方式实现,但有时候我们不得不采用操作系统的消息通信机制,例如在和底层语言开发的DLL交互时,是比较方便的.下面列举了一些实现方式,供大家参考:一.通过SendMes ...

  5. 安装 adobe flash player

    安装方法:     1. 下载Adobe Flash Player:        http://fpdownload.macromedia.com/get/flashplayer/pdc/11.2. ...

  6. stagefright框架(二)- 和OpenMAX的運作

    Stagefright的編解碼功能是利用OpenMAX框架,而且用的還是OpenCORE之OMX的實作,我們來看一下Stagefright和OMX是如何運作的. (1) OMX_Init OMXCli ...

  7. float 浮点数与零值0比较大小

    float x: 千万不要写x==0; 写出float x 与“零值”比较的if语句——一道面试题分析 写出float  x 与“零值”比较的if语句 请写出 float  x 与“零值”比较的 if ...

  8. js 抛物线 笔记备份

    var funParabola = function(element, target, options) { /* * 网页模拟现实需要一个比例尺 * 如果按照1像素就是1米来算,显然不合适,因为页面 ...

  9. 【java】之类加载机制

    类加载: 类加载机制是指.class文件加载到jvm,并形成Class对象的机制,之后的应用就可对Class对象进行实例化并调用,类加载机制可在运行时动态加载外部的类,远程网络下载过来的class文件 ...

  10. Xcode基本设置系列和Xcode报错解决方案

    1, arc机制中调用非arc文件. Xcode——>Project->Build Phases,将需要非arc文件更改为:"-fno-objc-arc"   ,该参数 ...