学习 NodeJS 4-Vue-Resource&Axios

4 Vue-Resource & Axios

4.1 Vue-Resource基础介绍

sdn方式加载 vue-resource.min.js

通过npm的方式:npm install vue-resource --save

vue-resource 的请求API是按照REST风格设计的,它提供了7种请求API:get、head、delete、jsonp、post、put、patch

全局拦截器 interceptors

Get:

get:function () {
  this.$http.get("package.json",{
    params:{
      uesrId:"101"
    },
    headers:{
      token:"abcd"
    }
  }).then(res=>{
    this.msg = res.data;
  },error=>{
    this.msg = error;
  });
},

Post:

post:function () {
  this.$http.post("package.json",{
    userId:"102"
  },{
    headers:{
      access_token:"abc"
    }
  }).then(function (res) {
    this.msg = res.data;
  });
},

JSONP:

jsonp:function () {
  this.$http.jsonp("http://www.imooc.com/course/AjaxCourseMenbers?ids=796").then(function (res) {
    this.msg = res.data;
  });
}

类似于Ajax的请求方式Http:

http:function () {
  this.$http({
    url:"package.json",
    method:"get",
    params:{
      userId:"103"
    },
    headers: {
      token: "123"
    },
    timeout:5,
    before:function () {
      console.log("before init.");
    }
  }).then(function (res) {
    this.msg = res.data;
  });
}

Interceptors: 

mounted:function(){
  Vue.http.interceptors.push(function (request,next) {
    console.log("request init.");
    next(function (response) {
      console.log("response init.");
      return response;
    })
  })
},

4.2 Axios 基础介绍

cdn引用axios

npm install axios --save

axios提供了将近8个API:request、get、delete、head、options、post、put、patch。

Get:

get:function () {
  axios.get("../package.json",{
    params:{
      userId:"999"
    },
    headers:{
      token:"jack"
    }
  }).then(res =>{
    this.msg = res.data;
  }).catch(function (error) {
    console.log("error:"+error)
  })
},

Post:

post:function () {
  axios.post("../package.json",{
    userId:"888"
  },{
    headers:{
      token:"Tom"
    }
  }).then(res=>{
    this.msg = res.data;
  }).catch(error=>{
    console.log("error:"+error);
  })
}

Http:

注:post发送的是request的body,get是发送的request的params。所以数据传送的时候post用data,get用params。

http:function () {
  axios({
    url:"../package.json",
    method:"post",
    params:{
      userId:"get"
    },
    data:{
      userId:"post"
    },
    headers:{
      token:"http-token"
    }
  }).then(res=>{
    this.msg = res.data;
  })
}

Interceptors: request在请求之前拦截,response在返回数据的时候拦截

mounted:function(){
  axios.interceptors.request.use(function (request) {
    console.log("request init.");
    return request;
  })
  axios.interceptors.response.use(function (response) {
    console.log("response init.")
    return response;
  })
},

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值