Vue:带有Axios的JWT授权标头

时间:2019-09-20 14:33:45

标签: vue.js cors token

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

比发出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”)返回正确的令牌。 我的问题是使用邮递员客户端不会遇到错误,并且当我作为授权值传递时,与标头/授权中的值相同

1 个答案:

答案 0 :(得分:0)

我将此代码替换为:

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);
    });
},