javascript 我应该如何在 axios GET 请求中发送 JWT 令牌?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52292441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I send JWT token in axios GET request?
提问by Babr
I'm new to Vue.js and want to make a request in a component to a restricted api:
我是 Vue.js 的新手,想在组件中向受限制的 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))
},
The problem is that I don't know how to include the token into the request header. So not surprisingly I get 401error in response.
问题是我不知道如何将令牌包含在请求标头中。所以毫不奇怪,我收到401错误响应。
And when I try
当我尝试
axios.defaults.headers.common['Authorization'] = this.token;
before the get request I receive OPTIONS /profile/meinstead of GET /profile/mein the server logs.
在我收到的 get 请求之前,OPTIONS /profile/me而不是GET /profile/me在服务器日志中。
How can I fix it?
我该如何解决?
回答by Lê Quang B?o
Axios get()request accept two parameter. So, beside the url, you can also put JWT in it.
axiosget()请求接受两个参数。因此,除了 url,您还可以将 JWT 放入其中。
axios.get(yourURL, yourConfig)
.then(...)
In your case yourConfigmight be something like this
在你的情况下yourConfig可能是这样的
yourConfig = {
headers: {
Authorization: "Bearer " + yourJWTToken
}
}
Also you can read about what you can put in your config here https://github.com/axios/axios. Just search for "Request Config"
您还可以在https://github.com/axios/axios阅读有关可以在配置中放入的内容的信息。只需搜索“请求配置”
回答by Praveen Poonia
This works for me, try like -
这对我有用,试试 -
let JWTToken = 'xxyyzz';
axios
.get(this.BASE_URL + '/profile/me', { headers: {"Authorization" : `Bearer ${JWTToken}`} })
.then(res => {
this.profile = res.data;
console.log('profile is:', res.data);
})
.catch(error => console.log(error))

