这是我参与8月更文挑战的第3天,活动详情查看:8月更文挑战html
Axios 是一个基于 promise 的 HTTP 库,能够用在浏览器和 node.js 中。本质其实就是ajax请求。node
对于这些功能特色的话,没有必要去死记硬背,在后面的实践中能够慢慢体会到。ios
npm安装:ajax
npm install axios
npm
cdn引入:json
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios
为了更好的操做,咱们首先建立一个测试端口和数据。api
json-server
npm install -g json-server
promise
db.json
文件{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
复制代码
3.运行json文件浏览器
json-server --watch db.json
4.打开网址,能够对里面数据进行请求
http://localhost:3000
5.而后建立一个基本的html文件,cdn引入axios,这里我建立了几个按钮,方便对数据进行操做
<div>
<button onclick="getData()">get</button>
<button onclick="postData()">post</button>
<button onclick="deleteData()">delete</button>
<button onclick="putData()">put</button>
</div>
复制代码
axios有两种请求的方式,axios做为函数执行发送请求,还有一种是调用方法。
axios(config)
axios(url[, config])
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
复制代码
//这里都使用了两种方法请求
function getData(){
// axios.get('http://localhost:3000/posts?id=1').then(res=>{
// console.log(res.data)
// }).catch(err=>{
// console.log(err.data)
// })
//没有指定method时,默认方法为get
axios({
url:"http://localhost:3000/posts",
params:{
id:1
}
}).then(res=>{
console.log(res.data)
})
}
复制代码
function postData(){
// axios({
// url:"http://localhost:3000/posts",
// method:'post',
// data:{
// title: "json-server2",
// author: "typicode2"
// }
// }).then(res=>{
// console.log(res.data)
// })
axios.post('http://localhost:3000/posts',{"title": "json-server2","author": "typicode2"})
.then(res=>{
console.log(res.data)
})
}
复制代码
能够在db.json
文件中看到新增的数据
//能够指定默认路径
axios.defaults.baseURL="http://localhost:3000"
function deleteData(){
// axios({
// url:"/posts/2",
// method:"delete",
// }).then(res=>{
// console.log(res.data)
// }).catch(err=>{
// console.log(err)
// })
axios.delete('/posts/2').then(res=>{
console.log(res.data)
},err=>{
console.log(err.data)
})
}
复制代码
其余的方法能够本身去测试,本身多写掌握得也会更快。
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';
复制代码
const instance=axios.create({
baseURL:"http://localhost:3000",
timeout:3000,
})
function getData(){
instance.get('/posts')
.then(res=>{
console.log(res.data)
})
}
复制代码
需求:项目中有部分接口须要的配置与另外一部分接口须要的配置不太同样
解决:建立两个新的instance,每一个都有本身特有的配置,分别应用到不一样要求的接口请求中
本篇文章主要是对一些axios的基本请求及实践操做,下一篇会涉及到拦截器、取消请求及简单的源码分析。axios升级篇(码住!)