如何从服务器响应中提取JWT令牌?

时间:2018-09-05 14:13:55

标签: javascript jwt axios

我想使用axios将JWT令牌fron表达回我的vue.js应用程序中。

这是我想出的:

 handleSubmit: function () {
            axios.post( this.BASE_URL + "/users/login", {
            username: this.username,
            password: this.password,
          }).then( (res) => { 
                console.log('res is:', res); //JWT found here 
                console.log('token is:', res.headers.common['Authorization']); //<-Problem here

                this.$router.push({ path: '/' });
           })
            .catch( (error) => {
            this.showErrorLogin = true;
            if (error) {
             this.error  = error;
             }  
          });

一个有趣的帖子之后,我在控制台中收到了这个消息:

      res is: {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}data: success: truetoken: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjViODZmOTE4YWNiMmI2Nzk3ZmEyYzFjNCIsInVzZXJuYW1lIjoiamFzZW0iLCJpYXQiOjE1MzYxNTgyNTAsImV4cCI6MTUzNjE5NDI1MH0.Sgl8cTHTQxU8rvBWdr365SBKABnUdbeUNHYLflqXURM"__proto__: Objectheaders: {content-type: "application/json; charset=utf-8"}request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}status: 200statusText: "OK"__proto__: Object


token is: undefined

但是我不知道如何提取它。我也尝试过res.headers['Authorization'],但获得了undefined

1 个答案:

答案 0 :(得分:1)

令牌可以通过多种方式传递

let fruits = ["apple","banana"]
print("result-\(fruits[safe : 2])")