vue2-axios

下载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);
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值