下载axios
开发版本:axios.js
生产版本:axios.min.js
搭建服务器:json-server
- npm i -g json-server
- json-server --watch db.json(启动服务并读取文件,db.json文件目录下启动)
json-server --watch db.json --port 3000(指定端口) - 访问:
http://localhost:3000(首页)
http://localhost:3000/posts(读取文件所有数据)
http://localhost:3000/posts/1(读取id为1的数据) - db.json
{
"posts" : [
{
"title" : "title1",
"anthor" : "anthor1",
"id" : 1
},
{
"title" : "title2",
"anthor" : "anthor2",
"id" : 2
}
]
}
基本使用
<script src="../axios.js"></script>
<script src="../vue.js"></script>
<div id="app1">
<button @click="search">get</button>
<button @click="add">add</button>
<ol>
<li v-for="item in postList" :key="item.id">
{{item.title}} {{item.author}}
<button @click="remove(item.id)">delete</button>
</li>
</ol>
</div>
<script>
// 全局默认值
// 基路径
axios.defaults.baseURL = "http://localhost:3000";
// 超时时间
axios.defaults.timeout = 10 * 1000// 毫秒
// 请求头配置
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
new Vue({
el:'#app1',
data : {
postList : []
},
methods : {
search(){
axios.get('/posts')
.then(res => {
console.log(res);// 请求成功
this.postList = res.data;
}).catch(reason => {
console.log(reason);// 请求失败
});
},
add(){
axios.post('/posts',{
title : "add",
author : "zhangsan"
}).then(res => {
console.log(res);
}).catch(reason => {
console.log(reason);
});
},
// 异步写法
async remove(id){
try{
await axios.delete('/posts/' + id);
}catch (e) {
console.log(e);
}
}
}
});
</script>
拦截器
// 请求拦截器
axios.interceptors.request.use(function(config){
console.log(config.method + " : " + config.url)
congif.url = config.url + "?token=xxx";
// 必须返回请求配置对象
return config;
},function(err){
console.log(err);
})
// 响应拦截器
axios.interceptors.response.use(function(response){
response.data.id = 1;
// 返回响应对象
return response;
},function(err){
console.log(err);
})