學習 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;
  })
},

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章