Vue.js使用vue-resource单击事件两次

时间:2017-02-01 13:05:22

标签: vuejs2 vue-component vue-resource

当我点击按钮触发我的功能时,我的请求被调用两次,正在调用api端点,在第一次请求时,我的授权令牌不包括在内,并且在第二次请求时它是,并且我收到错误401未经授权在控制台上。

错误:

  

XMLHttpRequest无法加载http://api.myurl.dev/educational/filials。预检的响应具有无效的HTTP状态代码401

当我在我的api上使用var_dump(getallheaders()); die;时,我可以看到这两个请求

enter image description here

这是我在 main.js 中的代码:

import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import Vuex from 'vuex'
import router from './router/routes.js'
import App from './App.vue'

const TOKEN = 'eyJ0eXAiO...'

Vue.use(VueRouter)
Vue.use(VueResource)
Vue.use(Vuex)

/* eslint-disable no-new */

// Start
new Vue({
  router,
  el: '#app',
  render: h => h(App)
})

Vue.http.interceptors.push((request, next) => {
  // modify headers
  request.headers.set('Authorization', 'Bearer ' + TOKEN)
  request.headers.set('Accept', 'application/json')
  next()
})

和我的 App.vue

<template>
     <div id="app">
        <img src="./assets/logo.png" alt="">
        <button type="button" @click="getFilial">Get Filial</button>
      </div>
</template>

<script>
  export default {
    methods: {
      data () {},
      getFilial () {
        this.$http.get('http://api.myurl.dev/educational/filials').then(response => {
          console.log(response.data)
        })
      }
    }
  }
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

这是我在第一次请求时使用var_dump得到的:

array (size=10)
  'Host' => string 'api.uniesp.dev' (length=14)
  'Connection' => string 'keep-alive' (length=10)
  'Access-Control-Request-Method' => string 'GET' (length=3)
  'Origin' => string 'http://localhost:8080' (length=21)
  'User-Agent' => string 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36' (length=108)
  'Access-Control-Request-Headers' => string 'authorization' (length=13)
  'Accept' => string '*/*' (length=3)
  'Referer' => string 'http://localhost:8080/' (length=22)
  'Accept-Encoding' => string 'gzip, deflate, sdch' (length=19)
  'Accept-Language' => string 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4' (length=35)

这就是我得到的第二个请求(正确):

array (size=9)
  'Host' => string 'api.uniesp.dev' (length=14)
  'Connection' => string 'keep-alive' (length=10)
  'Accept' => string 'application/json' (length=16)
  'Origin' => string 'http://localhost:8080' (length=21)
  'User-Agent' => string 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36' (length=108)
  'Authorization' => string 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi' (length=577)
  'Referer' => string 'http://localhost:8080/' (length=22)
  'Accept-Encoding' => string 'gzip, deflate, sdch' (length=19)
  'Accept-Language' => string 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4' (length=35)

0 个答案:

没有答案