我正在try 设置一个Vuejs前端应用程序(vue cli网页包模板),使其位于我的Larvel API之上.

通过提供正确的身份验证令牌,我可以通过vue资源从API获得成功响应,例如:

methods: {
    getUser () {
      this.$http.get('http://localhost:8000/api/user', 
      {
        headers: {
          'Authorization': 'Bearer eyJ0e.....etc',
          'Accept': 'application/json'
        }
      }).then((response) => {
        this.name = response.data.name
      });
    },

然而,我现在正在try 设置拦截器,以便 for each 请求自动添加用户的身份验证令牌.

基于vue资源自述,我将在我的main.js页中try 这一点:

Vue.use(VueResource)

Vue.http.interceptors.push((request, next) => {
  request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
  request.headers['Accept'] = 'application/json'
  next()
})

然后回到我的组件中,我现在有:

this.$http.get('http://localhost:8000/api/user').then((response) => {
    this.name = response.data.name
});

Problem:

当我在get本身中指定头时,我得到了一个成功的响应,但当我将它们传递到interceptor时,我从服务器返回了401 Unauthorized.如何在使用拦截器时修复此问题以成功响应?

Edit:

当通过向$http.get提供报头来发出请求时,我发出了一个成功的OPTIONS请求,然后是一个成功的GET请求,其中Authentication报头被提供给了GET请求.

然而,当我直接从$http.get中删除头并将其移动到拦截器时,我只发出GET请求,而GET不包含Authentication头,因此返回为401 Unauthorized.

推荐答案

事实证明,我的问题是我在拦截器中设置头的语法.

应该是这样的:

Vue.use(VueResource)

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

当我这么做的时候:

Vue.use(VueResource)

Vue.http.interceptors.push((request, next) => {
  request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
  request.headers['Accept'] = 'application/json'
  next()
})

Vue.js相关问答推荐

可组合数据获取示例

Nuxt3 / Vue3 - 当属性更改时如何动态更改渲染组件?

vue3 输入标签给出错误 Vue.use 不是函数

绑定事件在渲染函数中不起作用

Nuxt 和 Vite 有什么区别?

如何在 VUE.js 中重新刷新时保持多层 b-collapse 菜单打开?

webpack vue-loader 配置

VueJS - 将单独的组件加载到 vue 实例中

如何在 Vuetify v-data-table 上对齐标题

在 VueJS 中存储图像的正确位置是什么 - 公共文件夹或assets文件夹?

如何为 Vue 应用提供 robots.txt

vuex 中 { dispatch, commit } 的类型是什么?

如何更新手动安装的 vue 组件上的props?

在基于 TypeScript 的 Vue 中将 vuex 状态和Mutations绑定到复选框组件属性

在组件外使用 VueI18n 的问题

取消选中单选按钮

Vue.js 单向绑定表单

依赖关系甚至在 package.json 和 node_modules 中都没有定义

使密码字符隐藏在 Vuetify 字段中

带有 Firebase 云消息传递的 Vue pwa 无法正常工作