Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

相关特性:

  • 从浏览器创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防御XSRF
    ​​​axios中文网​
基本使用案例:

(使用时需要引入axios文件)

<!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">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<title>axios练习</title>
</head>

<body>

</body>
<script>
axios.get('http://localhost:3000/axios/').then(
res => {
console.log(res)
console.log(res.data);
}
)
</script>

</html>

axios起步_vue.js


多层接口调用:

axios.get('http://localhost:3000/axios/').then(
res => {
console.log(res.data);
// return 一个promise对象
return axios.get('http://localhost:3000/axios/axios_test1')
}
).then(res => {
// 接收axios_test1接口传来的数据
console.log(res.data);
});

axios起步_ios_02

axios将请求方式封装好可以直接拿来 用

//get方式
axios.get('xxxxx').then();
//post方式
axios.post('xxxx').then();
//put方式
axios.put('xxxx').then();
//delete方式
axios.delete('xxx').then();

axios get和delete的三种传参方式:

①普通型
②restful
③params

axios.get('http://localhost:3000/axios/paramsMethods?id=123').then(
res => {
console.log("普通方式" + res.data);
}
)
// restful
axios.get('http://localhost:3000/axios/paramsMethods/123').then(
res => {
console.log("restfull方式" + res.data);
}
)
// params方式
axios.get('http://localhost:3000/axios/paramsMethods', {
params: {
id: 456
}
}).then(
res => {
console.log("params方式" + res.data);
}
)
服务器端:
router.get('/paramsMethods', (req, res, next) => {
// 普通方式和param都是用req.query来查询
res.send(req.query.id)
})
router.get('/paramsMethods/:id', (req, res, next) => {
res.send(req.params.id)
})
演示结果:

axios起步_前端_03

axios post和put的两种传参方式: