我应该如何在axios GET请求中发送JWT令牌? [英] How should I send JWT token in axios GET request?

查看:155
本文介绍了我应该如何在axios GET请求中发送JWT令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Vue.js的新手,想在组件中向受限api请求:

I'm new to Vue.js and want to make a request in a component to a restricted api:

  computed: {
    token () {
      return this.$store.getters.getToken; 
    },
   ...

created () {
         axios
        .get( this.BASE_URL + '/profile/me')
        .then( res => {
                    this.profile = res.data;
                    console.log('profile is:', res.data);

          })
          .catch(error => console.log(error))            
    },

问题是我不知道如何将令牌包括在请求标头中.因此,在响应中出现 401 错误就不足为奇了.

The problem is that I don't know how to include the token into the request header. So not surprisingly I get 401 error in response.

当我尝试

axios.defaults.headers.common['Authorization'] = this.token;

在获取请求之前,我在服务器日志中收到了 OPTIONS/profile/me 而不是 GET/profile/me .

before the get request I receive OPTIONS /profile/me instead of GET /profile/me in the server logs.

我该如何解决?

推荐答案

Axios get()请求接受两个参数.因此,您可以在网址旁边添加JWT.

Axios get() request accept two parameter. So, beside the url, you can also put JWT in it.

axios.get(yourURL, yourConfig)
.then(...)

在您的情况下, yourConfig 可能是这样的

In your case yourConfig might be something like this

yourConfig = {
   headers: {
      Authorization: "Bearer " + yourJWTToken
   }
}

此外,您还可以在此处阅读有关可在配置中添加的内容的信息 https://github.com/axios/axios.只需搜索请求配置"

Also you can read about what you can put in your config here https://github.com/axios/axios. Just search for "Request Config"

这篇关于我应该如何在axios GET请求中发送JWT令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆