【问题标题】:Vue.js log API endpoint response with vue-resourceVue.js 使用 vue-resource 记录 API 端点响应
【发布时间】:2017-01-31 16:06:50
【问题描述】:

我正在尝试在我的组件中记录 API 响应只是为了测试目的,但我仍然收到错误 401(未经授权),我在本地主机中执行此操作,我的 API 也托管在本地主机中,但只是使用虚拟主机网址,所以我得到了这个:http://api.myurl.dev

我正在使用 vue-cli 在 localhost:8080 中运行我的 vue。

这是我的代码,我的 ma​​in.js

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

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

/* eslint-disable no-new */

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

// Bearer token auth
Vue.http.interceptors.push((request, next) => {
  request.headers.set('Authorization', 'Bearer eyJ0...')
  request.headers.set('Accept', 'application/json')
  next()
})

还有我的App.vue

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

<script>
  export default {
    data () {
      return {
        context: 'app context',
        loaded: false
      }
    },
    methods: {
      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>

【问题讨论】:

    标签: javascript vuejs2


    【解决方案1】:

    通过 vue-resource 触发您的 API,它实际上是在向您的前端应用程序回应您无权使用它,并带有适当的 HTTP 401 状态代码。

    专注于您的后端 API!您的前端应用程序运行良好,并且实际上与您的 API 通信,它回答“401”:)

    也许您的标头 (Authorization: Bearer eyJ0...) 没有按照您的 API 的预期格式设置,但再次关注您的 API 来调试它!

    【讨论】:

    • 我正在使用一个名为 Postman 的应用程序来测试我的 api,它运行良好..
    • 太棒了!你能分享一下你的邮递员“授权”和“标题”标签的截图吗?
    • 另外,您是否在浏览器控制台中验证了发送到您的 API 的实际请求?它真的与您的标头一起提供吗?
    • 在你提到之后,我发现问题出在我的 apache httpd-vhosts.conf,我需要设置我的请求标头。所以我放了这个,现在它正在工作Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" Header set Access-Control-Allow-Headers "*, Authorization"
    猜你喜欢
    • 2017-04-27
    • 2017-05-27
    • 2019-01-31
    • 2020-03-23
    • 2021-11-14
    • 1970-01-01
    • 2021-10-02
    • 2017-11-20
    • 2019-11-12
    相关资源
    最近更新 更多