无法在标头中发送授权令牌

时间:2018-03-08 03:40:18

标签: vue.js axios

我正在尝试向API发送一个put请求。为了使它工作,我必须在标题中发送一个授权令牌。

这是我的代码:

 updatePlaylist(id, name) {
    axios.put(`${config.baseUrl}/playlists/${id}`, { headers: auth.getAuthHeader(), data: { name } })
      .then(() => {
      })
      .catch(() => {
        console.error('unable to update tasks');
      });
  },

这里是getAuthHeader函数:

getAuthHeader() {
    console.log(localStorage.getItem('token'));
    return {
      Authorization: localStorage.getItem('token')
    };
  }

getAuthHeader函数返回的标记是好的。

现在问题是我总是得到401错误,标题中没有授权。而不是那样,我在使用Google Chrome检查员检查时,在“请求有效负载”部分中看到了这一点:

{headers: {,…}, data: {name: "test"}}
data
:
{name: "test"}
headers
:
{,…}

出于某种原因,我的标题随数据一起发送。

任何人都知道如何修复它?

非常感谢

1 个答案:

答案 0 :(得分:1)

您调用data的方式不正确。您正在put方法的config中传递标题,您需要将其作为axios.put(`${config.baseUrl}/playlists/${id}`, { name }, { headers: {...getAuthHeader() //, {...otherHeaders} Incase you have to add other headers as well } }) 参数发送。

headers
  

使用别名方法(post,put,get)时,不需要在config中指定url,method和data属性。但有关GetUserData(){ this.userService.GetUserDetails().subscribe(data=>{ if(Array.isArray(data)) this.user=data; console.log(this.user); }); } 的信息仍将转到配置参数。

相关问题