【问题标题】:Vue : JWT Authorization header with AxiosVue:带有 Axios 的 JWT 授权标头
【发布时间】:2019-09-20 14:33:45
【问题描述】:

我在 vue.js 上创建了一个前端应用程序,并使用 phoenix 作为后端。 我尝试发出请求并返回错误: GET http://localhost:4000/api/v1/my_user401(未授权)

这比遇到 CORS 问题要好。

在我的脚本部分,我构建了我的标题来管理访问控制并通过授权。最后,我调用我的 URL 并传递变量。

getCurrentUser: function() {
  let axiosConfig = {
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      "Access-Control-Allow-Origin": "*",
      "Authorization": "Bearer " + localStorage.getItem("jwt")
    }
  };

  // call rest API
  axios
    .get("http://localhost:4000/api/v1/my_user", {}, axiosConfig)
    .then(res => {
      console.log("RESPONSE RECEIVED: ", res);
      //const jwt = res.data.jwt;
      //this.showComponent = false;
      console.log("res:" + res);
      //localStorage.setItem("jwt", jwt); // store the token in localstorage
    })
    .catch(err => {
      console.log("AXIOS ERROR: ", err);
    });
},

localStorage.getItem("jwt") 返回正确的令牌。 我的问题是我没有通过使用邮递员客户端遇到错误,并且当我作为授权值传递与标题/授权中相同的值时

【问题讨论】:

  • 可能是许多事情之一。您在后端收到哪些标头?您是否需要对其进行配置以删除承载文本,您是否尝试解析小写承载并传递承载。令牌是否有效,是否具有正确的权限等。
  • 从技术上讲,我收到了一个包含令牌值的 json。此令牌存储在 localStorage 中。我尝试了使用和不使用“Bearer”部分,我也解析了它,但错误保持不变。我试图用邮递员将令牌寄回并且它有效。我想知道我是否将授权放在它应该属于的地方。我试图将令牌作为 {} 之间的第二个参数

标签: vue.js token


【解决方案1】:

我将这段代码替换为:

getCurrentUser: function() {
    axios.defaults.headers.common["Authorization"] =
                "Bearer " + localStorage.getItem("jwt");

   // call rest API
    axios
        .get("http://localhost:4000/api/v1/my_user")
        .then(res => {
         console.log("RESPONSE RECEIVED: ", res);
    })
    .catch(err => {
        console.log("AXIOS ERROR: ", err);
    });
},

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 2019-05-30
    • 2016-01-22
    • 2020-07-26
    • 1970-01-01
    • 2015-11-05
    • 2017-11-23
    • 2017-08-18
    相关资源
    最近更新 更多