赞
踩
Axios 是什么?
Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
从浏览器创建 XMLHttpRequests
从 node.js 创建 http 请求
支持 Promise API
拦截请求和响应
转换请求和响应数据
取消请求
自动转换JSON数据
客户端支持防御XSRF
使用 npm:
$ npm install axios
使用 yarn:
$ yarn add axios
注意: CommonJS 用法
为了在CommonJS中使用 require() 导入时获得TypeScript类型推断(智能感知/自动完成),请使用以下方法:
const axios = require('axios').default;
// axios.<method> 能够提供自动完成和参数类型推断功能
const axios = require('axios');
// 向给定ID的用户发起请求
axios.get('/user?ID=12345')
.then(function (response) {
// 处理成功情况
console.log(response);
})
.catch(function (error) {
// 处理错误情况
console.log(error);
})
.then(function () {
// 总是会执行
});
// 上述请求也可以按以下方式完成(可选)
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// 总是会执行
});
// 支持async/await用法
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
注意: 由于async/await 是ECMAScript 2017中的一部分,而且在IE和一些旧的浏览器中不支持,所以使用时务必要小心。
发起一个 POST 请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
发起多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});
可以向 axios 传递相关配置来创建请求
axios(config)
// 发起一个post请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// 在 node.js 用GET请求获取远程图片
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
axios(url[, config])
// 发起一个 GET 请求 (默认请求方式)
axios('/user/12345');
请求方式别名
为了方便起见,已经为所有支持的请求方法提供了别名(常用摘录)。
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
注意:在使用别名方法时, url、method、data 这些属性都不必在配置中指定。
axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
一个请求的响应包含以下信息。
{
// `data` 由服务器提供的响应
data: {},
// `status` 来自服务器响应的 HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: 'OK',
// `headers` 是服务器响应头
// 所有的 header 名称都是小写,而且可以使用方括号语法访问
// 例如: `response.headers['content-type']`
headers: {},
// `config` 是 `axios` 请求的配置信息
config: {},
// `request` 是生成此响应的请求
// 在node.js中它是最后一个ClientRequest实例 (in redirects),
// 在浏览器中则是 XMLHttpRequest 实例
request: {}
}
当使用 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);
});
当使用 catch,或者传递一个rejection callback作为 then 的第二个参数时,响应可以通过 error 对象被使用,正如在错误处理部分解释的那样。
可以使用qs 库编码数据:
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
或者用ES6方式:
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue搭配axios简单测试案例</title>
<script src="js/vue.js"></script>
<script src="js/axios.js"></script>
</head>
<body>
<div id="app">
<table>
<tr v-for="item in userList">
<td>{{item.age}}</td>
<td>{{item.name}}</td>
</tr>
</table>
<p v-for="(item,index) in userList">{{item}}</p>
</div>
<script>
const app = new Vue({
el: "#app",
data: { //初始值
userList: []
},
created() { //渲染之前
//调用方法
this.getUserList()
},
methods: { //方法
//ajax请求
getUserList() {
//axios.defaults.baseURL = 'http://127.0.0:5500',
axios.get({
//请求本地json数据文件
url: 'testData.json',
headers: {
"Content-Type": "application/octet-stream",
"Access-Control-Allow-Origin": "*", //跨域问题配置
"CrossOrigin": true,
"secure": true // 如果是https接口,需要配置这个参数
}
}).then(response => {
console.log(response)
this.userList = response.data.data.items
}).catch(error => {
console.log(error)
})
}
}
})
</script>
</body>
</html>
testData.json
{
"success": "ok",
"code": 200,
"data": {
"items": [
{ "name": "lucy", "age": 20 },
{ "name": "marry", "age": 25 },
{ "name": "mark", "age": 30 }
]
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。