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>

猜你喜欢

转载自blog.csdn.net/weixin_41111068/article/details/84491110
今日推荐