[学习笔记] 数据请求(二) — Axios
认识 Axios
-
文档
-
概要说明
- Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
- 特性:
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
简单使用 Axios
一、安装
-
脚手架(npm)安装:
此处为当前写法,请以官网描述为准:
请前往 npm 官网 搜索 ‘axios’ —— Axios-npm
$ npm install axios
-
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
二、简单使用案例
2-1 请求案例
-
简单 get 请求
axios.get('https://jsonplaceholder.typicode.com/todos/1').then(res => { console.log(res.data); // 打印获取到的数据 }) .then(res => { console.log(res); // 打印获取到的数据 }) .catch(err => console.log(err));
-
post 请求
Ps: 使用 jsonplaceholder,资源不会在服务器上真正更新,但会被仿造。
所以:想展示上传数据后的数据,需要本地将返回结果
push
或者unshift
到本地数组中数据准备:
todo: { "title": "William", "completed": true }
发起请求:
axios.post('https://jsonplaceholder.typicode.com/todos', this.todo) .then(res => { console.log(res.data); // 打印获取到的数据 });
返回结果:
{ "id": 201, "title": "William", "completed": true }
-
写法二:(以 post 请求为例,数据同上
todo
)// 发送 POST 请求 axios({ method: 'post', url: 'https://jsonplaceholder.typicode.com/todos', data: this.todo, timeout: 5000 }) .then(res => console.log(res.data)) .catch(err => console.log(