还是那个开源项目中的代码看到的:

直接看axios官方的介绍吧,里面的用法介绍很全:

https://github.com/mzabriskie/axios

Installing

Using npm:

$ npm install axios

Using cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Example

Performing a GET request

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
}); // Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Performing a POST request

axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Performing multiple concurrent requests

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
}));

。。。

Response Schema

The response for a request contains the following information.

{
// `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
// All header names are lower cased
headers: {}, // `config` is the config that was provided to `axios` for the request
config: {}, // `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}
}

When using then, you will receive the response as follows:

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);
});

When using catch, or passing a rejection callback as second parameter of then, the response will be available through the error object as explained in the Handling Errors section.

Config Defaults

You can specify config defaults that will be applied to every request.

Global axios defaults

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';

Interceptors

You can intercept requests or responses before they are handled by then or catch.

// Add a request interceptor
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);
}); // Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});

If you may need to remove an interceptor later you can.

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

You can add interceptors to a custom instance of axios.

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

Handling Errors

axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});

You can define a custom HTTP status code error range using the validateStatus config option.

axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})

Cancellation

You can cancel a request using a cancel token.

The axios cancel token API is based on the withdrawn cancelable promises proposal.

You can create a cancel token using the CancelToken.source factory as shown below:

var CancelToken = axios.CancelToken;
var source = CancelToken.source(); axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
}); // cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

You can also create a cancel token by passing an executor function to the CancelToken constructor:

var CancelToken = axios.CancelToken;
var cancel; axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
}); // cancel the request
cancel();

Note: you can cancel several requests with the same cancel token.

 

javascript http库axios的更多相关文章

  1. ABP(现代ASP.NET样板开发框架)系列之21、ABP展现层——Javascript函数库

    点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之21.ABP展现层——Javascript函数库 ABP是“ASP.NET Boilerplate Project ...

  2. Webix JavaScript UI 库可以帮你构建跨平台的HTML5 和 CSS3 程序

    XB 软件公司最近发布了JavaScript UI 库Webix ,其中包含的组件超过45个,用这些组件可以构建跟HTML5 和 CSS3 兼容的程序,这些程序不仅能在个人电脑上运行,还能用在iOS. ...

  3. ECharts-基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据可视化图表

    ECharts http://ecomfe.github.com/echarts 基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据可视化图表.创新的拖拽重计算 ...

  4. 【精心推荐】几款实用的 JavaScript 图形图表库

    一款好的图表插件不是那么容易找到的.最近项目里需要实现统计图表功能,所以在网上搜罗了一圈,找到一些不错的图表插件,分享大家.众多周知,图形和图表要比文本更具表现力和说服力.这里给大家精心推荐几款实用的 ...

  5. Vis.js – 基于浏览器的动态 JavaScript 可视化库

    Vis.js 是一个动态的,基于浏览器的可视化库.该库被设计为易于使用,能处理大量的动态数据.该库由以下几部分组成:一是数据集和数据视图,基于灵活的键/值数据集,可以添加,更新和删除项目,订阅数据集变 ...

  6. 向 Web 开发人员推荐35款 JavaScript 图形图表库

    图表是数据图形化的表示,通过形象的图表来展示数据,比如条形图,折线图,饼图等等.可视化图表可以帮助开发者更容易理解复杂的数据,提高生产的效率和 Web 应用和项目的可靠性. 在这篇文章中,我们收集了3 ...

  7. 几款实用的 JavaScript 图形图表库

    一款好的图表插件不是那么容易找到的.最近项目里需要实现统计图表功能,所以在网上搜罗了一圈,找到一些不错的图表插件,分享大家.众多周知,图形和图表要比文本更具表现力和说服力.这里给大家精心推荐几款实用的 ...

  8. ECharts JavaScript图表库 ECharts

    ECharts开源来自百度商业前端数据可视化团队,基于html5 Canvas,是一个纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据可视化图表.创新的拖拽重计算.数据视图.值 ...

  9. ABP展现层——Javascript函数库

    ABP展现层——Javascript函数库 点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之21.ABP展现层——Javascript函数库 ABP是“ASP.N ...

随机推荐

  1. import详解

    试想一下 在工作中今年在一个项目中可能会导入某一个目录下的模块文件,那这个时候怎么样才能让Python解释器能够找到该模块进行调用呢? - 将这个模块拷贝一份到当前使用目录下. 这种方式让模块太冗余 ...

  2. Selenium2+python自动化60-异常后截图(screenshot)【转载】

    前言 在执行用例过程中由于是无人值守的,用例运行报错的时候,我们希望能对当前屏幕截图,留下证据. 在写用例的时候,最后一步是断言,可以把截图的动作放在断言这里,那么如何在断言失败后截图呢? 一.截图方 ...

  3. poj 2398(叉积判断点在线段的哪一侧)

    Toy Storage Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 5016   Accepted: 2978 Descr ...

  4. Mysql错误:Every derived table must have its own alias

    Mysql报错:Every derived table must have its own alias    <缺少一个别名> 在子查询中经常会犯的错误 .这个别名其实没啥用途....  ...

  5. HDU 1711 Number Sequence【kmp求子串首次出现的位置】

      Given two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2], ...... , b[M] (1 <= ...

  6. 学习LSM(Linux security module)之二:编写并运行一个简单的demo

    各种折腾,经过了一个蛋疼的周末,终于在Ubuntu14.04上运行了一个基于LSM的简单demo程序. 一:程序编写 先简单的看一下这个demo: //demo_lsm.c#include <l ...

  7. ba resme

    Resume Name: Zhou Heng Gender: Male Email : jackyzhouheng@gmail.com Self Assessment: I have more tha ...

  8. AtCoder - 2064 Many Easy Problems

    Problem Statement One day, Takahashi was given the following problem from Aoki: You are given a tree ...

  9. 【并查集】【set】AtCoder - 2159 - 連結 / Connectivity

    Problem Statement There are N cities. There are also K roads and L railways, extending between the c ...

  10. 【分块】【常数优化】【Orz faebdc】洛谷 P1083 NOIP2012提高组 借教室

    分块90分. By AutSky_JadeK [重点在下面] #include<cstdio> #include<cmath> using namespace std; #de ...