1. 程式人生 > >Vue vue-resource 全域性攔截器 Post、Get、Jsonp跨域請求、配置請求 全域性路徑配置

Vue vue-resource 全域性攔截器 Post、Get、Jsonp跨域請求、配置請求 全域性路徑配置

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="../node_modules/vue/dist/vue.js"></script>
  <script src="../node_modules/vue-resource/dist/vue-resource.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div id="app" class="container">
  <h1>vue-resource外掛講解</h1>
  <a href="javascript:;" class="btn btn-primary" v-on:click="get">Get請求</a>
  <a href="javascript:;" class="btn btn-primary" v-on:click="post">Post請求</a>
  <a href="javascript:;" class="btn btn-primary" v-on:click="jsonp">Jsonp請求</a>
  <a href="javascript:;" class="btn btn-primary" v-on:click="http">http</a>
  <div>
    <span>{{this.msg}}</span>
  </div>
</div>
<script>
 new Vue({
   el: '#app',
   data: {
     msg: ''
   },
   mounted () {
     Vue.http.interceptors.push((request, next) => {
       console.log('request init.');
       next(res => {
         console.log('response init.');
         return res
       })
     })
   },
   // 全域性路徑配置
   http: {
     root: 'http://localhost:63342/Imooc/ImoocMall/'
   },
   methods: {
     get () {
       this.$http.get('package.json', {
         params: {
           userId: '101'
         },
         // 請求頭注入 第三方很有用
         headers: {
           token: 'abcd'
         }
       }).then(res => {
         this.msg = res.data
       }, error => {
         console.log(error);
         this.msg = error
       })
     },
     post () {
       this.$http.post('package.json', {
         userId: '102'
       },{
         headers: {
           access_token: 'abc'
         }
       }).then(res => {
         this.msg = res.data
       }, error => {
         this.msg = error
       })
     },
     jsonp () {
       this.$http.jsonp('https://www.imooc.com/course/ajaxcoursenewrecom?cid=980').then(res => {
         this.msg = res.data
       }, error => {
         this.msg = error
       })
     },
     // 配置
     http () {
       this.$http({
         url:'package.json',
         params: {
           userId: '103'
         },
         headers: {
           token: '123'
         },
         timeout: 5,
         before: function () {
           console.log('before init.')
         }
       }).then(res => {
         this.msg = res.data
       })
     }
   }
 })
</script>
</body>
</html>