页面中怎么获取 axios的axios post timeoutt

在Vue1.0的时候有一个官方推荐的 ajax 插件&,但是自从 Vue 更新到 2.0 之后,官方就不再更新 vue-resource。
关于为什么放弃推荐? -& 尤大原话
最近团队讨论了一下,Ajax 本身跟 Vue 并没有什么需要特别整合的地方,使用 fetch polyfill 或是 axios、superagent 等等都可以起到同等的效果,
vue-resource 提供的价值和其维护成本相比并不划算,所以决定在不久以后取消对 vue-resource 的官方推荐。已有的用户可以继续使用,
但以后不再把 vue-resource 作为官方的 ajax 方案。这里可以去掉 vue-resource,文档也不必翻译了。
目前主流的 Vue 项目,都选择&&来完成 ajax 请求,下面来具体介绍一下axios的使用。
axios 简介
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
从浏览器中创建 XMLHttpRequest
从 node.js 发出 http 请求
支持 Promise API
拦截请求和响应
转换请求和响应数据
自动转换JSON数据
客户端支持防止&
引入方式:
$ npm install axios//使用淘宝源
$ cnpm install axios
//或者使用cdn:
&script src="/axios/dist/axios.min.js"&&/script&
安装其他插件的时候,可以直接在 main.js 中引入并使用 Vue.use()来注册,但是 axios并不是vue插件,所以不能 使用Vue.use(),所以只能在每个需要发送请求的组件中即时引入。
为了解决这个问题,我们在引入 axios 之后,通过修改原型链,来更方便的使用。
import axios from 'axios'
Vue.prototype.$http = axios
在 main.js 中添加了这两行代码之后,就能直接在组件的 methods 中使用 $http命令
methods: {
postData () {
this.$http({
method: 'post',
url: '/user',
name: 'xiaoming',
info: '12'
下面来介绍axios的具体使用:
执行 GET 请求
// 向具有指定ID的用户发出请求
$http.get('/user?ID=12345')
.then(function (response) {
console.log(response);
.catch(function (error) {
console.log(error);
// 也可以通过 params 对象传递参数
$http.get('/user', {
.then(function (response) {
console.log(response);
.catch(function (error) {
console.log(error);
执行 POST 请求
$http.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
.then(function (response) {
console.log(response);
.catch(function (error) {
console.log(error);
执行多个并发请求
function getUserAccount() {
return $http.get('/user/12345');
function getUserPermissions() {
return $http.get('/user/12345/permissions');
axios.all([getUserAccount(), getUserPermissions()])
.then($http.spread(function (acct, perms) {
//两个请求现已完成
可以通过将相关配置传递给 axios 来进行请求。
axios(config)
// 发送一个 POST 请求
method: 'post',
url: '/user/12345',
firstName: 'Fred',
lastName: 'Flintstone'
axios(url[, config])
// 发送一个 GET 请求 (GET请求是默认请求模式)
axios('/user/12345');
请求方法别名
为了方便起见,已经为所有支持的请求方法提供了别名。
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]])
注意当使用别名方法时,不需要在config中指定url,method和data属性。
帮助函数处理并发请求。
axios.all(iterable)
axios.spread(callback)
您可以使用自定义配置创建axios的新实例。
axios.create([config])
var instance = axios.create({
baseURL: '/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是必需的。 如果未指定方法,请求将默认为GET。
// `url`是将用于请求的服务器URL
url: '/user',
// `method`是发出请求时使用的请求方法
method: 'get', // 默认
// `baseURL`将被添加到`url`前面,除非`url`是绝对的。
// 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。
baseURL: '/api/',
// `transformRequest`允许在请求数据发送到服务器之前对其进行更改
// 这只适用于请求方法'PUT','POST'和'PATCH'
// 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream
transformRequest: [function (data) {
// 做任何你想要的数据转换
// `transformResponse`允许在 then / catch之前对响应数据进行更改
transformResponse: [function (data) {
// Do whatever you want to transform the data
// `headers`是要发送的自定义 headers
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params`是要与请求一起发送的URL参数
// 必须是纯对象或URLSearchParams对象
// `paramsSerializer`是一个可选的函数,负责序列化`params`
// (e.g. /package/qs, /jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
// `data`是要作为请求主体发送的数据
// 仅适用于请求方法“PUT”,“POST”和“PATCH”
// 当没有设置`transformRequest`时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
firstName: 'Fred'
// `timeout`指定请求超时之前的毫秒数。
// 如果请求的时间超过'timeout',请求将被中止。
timeout: 1000,
// `withCredentials`指示是否跨站点访问控制请求
// should be made using credentials
withCredentials: false, // default
// `adapter'允许自定义处理请求,这使得测试更容易。
// 返回一个promise并提供一个有效的响应(参见[response docs](#response-api))
adapter: function (config) {
// `auth'表示应该使用 HTTP 基本认证,并提供凭据。
// 这将设置一个`Authorization'头,覆盖任何现有的`Authorization'自定义头,使用`headers`设置。
username: 'janedoe',
password: 's00pers3cret'
// “responseType”表示服务器将响应的数据类型
// 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
//`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName`是携带xsrf令牌值的http头的名称
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress`允许处理上传的进度事件
onUploadProgress: function (progressEvent) {
// 使用本地 progress 事件做任何你想要做的
// `onDownloadProgress`允许处理下载的进度事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
// `maxContentLength`定义允许的http响应内容的最大大小
maxContentLength: 2000,
// `validateStatus`定义是否解析或拒绝给定的promise
// HTTP响应状态码。如果`validateStatus`返回`true`(或被设置为`null` promise将被解析;否则,promise将被
validateStatus: function (status) {
return status &= 200 && status & 300; // default
// `maxRedirects`定义在node.js中要遵循的重定向的最大数量。
// 如果设置为0,则不会遵循重定向。
maxRedirects: 5, // 默认
// `httpAgent`和`httpsAgent`用于定义在node.js中分别执行http和https请求时使用的自定义代理。
// 允许配置类似`keepAlive`的选项,
// 默认情况下不启用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy'定义代理服务器的主机名和端口
// `auth`表示HTTP Basic auth应该用于连接到代理,并提供credentials。
// 这将设置一个`Proxy-Authorization` header,覆盖任何使用`headers`设置的现有的`Proxy-Authorization` 自定义 headers。
host: '127.0.0.1',
port: 9000,
username: 'mikeymike',
password: 'rapunz3l'
// “cancelToken”指定可用于取消请求的取消令牌
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
使用 then 时,您将收到如下响应:
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 = '';
axios.mon['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
你可以截取请求或响应在被 then 或者 catch 处理之前
//添加请求拦截器
axios.interceptors.request.use(function(config){
//在发送请求之前做某事
},function(error){
//请求错误时做些事
return Promise.reject(error);
//添加响应拦截器
axios.interceptors.response.use(function(response){
//对响应数据做些事
},function(error){
//请求错误时做些事
return Promise.reject(error);
axios.get('/ user / 12345')
.catch(function(error){
if(error.response){
//请求已发出,但服务器使用状态代码进行响应
//落在2xx的范围之外
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
//在设置触发错误的请求时发生了错误
console.log('Error',error.message);
console.log(error.config);
您可以使用validateStatus配置选项定义自定义HTTP状态码错误范围。
axios.get('/ user / 12345',{
validateStatus:function(status){
return status & 500; //仅当状态代码大于或等于500时拒绝
使用application / x-www-form-urlencoded格式
默认情况下,axios将JavaScript对象序列化为JSON。 要以应用程序/ x-www-form-urlencoded格式发送数据,您可以使用以下选项之一。
在浏览器中,您可以使用URLSearchParams API,如下所示:
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
请注意,所有浏览器都不支持URLSearchParams,但是有一个polyfill可用(确保polyfill全局环境)。
或者,您可以使用qs库对数据进行编码:
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });
查看更多 请访问我的独立博客&
阅读(...) 评论()34912人阅读
javascript(10)
基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用
在浏览器中发送&&请求在 node.js 中发送&请求支持&&API拦截请求和响应转换请求和响应数据自动转换 JSON 数据客户端支持保护安全免受&&攻击
浏览器支持
使用 bower:
$ bower install axios
$ npm install axios
发送一个&GET&请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
.catch(function (response) {
console.log(response);
axios.get('/user', {
.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) {
可以通过给&axios传递对应的参数来定制请求:
axios(config)
method: 'post',
url: '/user/12345',
firstName: 'Fred',
lastName: 'Flintstone'
axios(url[, config])
axios('/user/12345');
请求方法别名
为方便起见,我们为所有支持的请求方法都提供了别名
axios.get(url[, config])
axios.delete(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: '/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
所有可用的实例方法都列在下面了,指定的配置将会和该实例的配置合并。
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
下面是可用的请求配置项,只有&url&是必需的。如果没有指定&method&,默认的请求方法是&GET。
url: '/user',
method: 'get',
baseURL: '/api/',
transformRequest: [function (data) {
return data;
transformResponse: [function (data) {
return data;
headers: {'X-Requested-With': 'XMLHttpRequest'},
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
firstName: 'Fred'
timeout: 1000,
withCredentials: false,
adapter: function (resolve, reject, config) {
username: 'janedoe',
password: 's00pers3cret'
responseType: 'json',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
progress: function(progressEvent) {
响应的数据结构
响应的数据包括下面的信息:
status: 200,
statusText: 'OK',
headers: {},
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 = '';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
自定义实例默认配置
var instance = axios.create({
baseURL: ''
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.
var instance = axios.create();
instance.defaults.timeout = 2500;
instance.get('/longRequest', {
timeout: 5000
你可以在处理&then&或&catch&之前拦截请求和响应
axios.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
axios.interceptors.response.use(function (response) {
return response;
}, function (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) {
console.log('Error', response.message);
console.log(response.data);
console.log(response.status);
console.log(response.headers);
console.log(response.config);
axios 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入&
TypeScript
axios 包含一个&&定义
/// &reference path=&axios.d.ts& /&
import * as axios from 'axios';
axios.get('/user?ID=12345');
axios is heavily inspired by the&&provided in&.
Ultimately axios is an effort to provide a standalone&$http-like service for use outside
of Angular.
转载:/repo/mzabriskie/axios
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:52992次
排名:千里之外
原创:10篇
转载:22篇
(1)(1)(1)(3)(8)(1)(1)(13)(3)
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'你可能感兴趣的文章
扫描二维码用手机看文章

我要回帖

更多关于 axios timeout cancel 的文章

 

随机推荐