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

查看:45
本文介绍了我应该如何在 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() 请求接受两个参数.所以,除了url,你也可以把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天全站免登陆