我的应用程序中有许多帖子请求。其中一些必须具有并使用 token
提取 header 我不确定如何附加它
到目前为止,我的代码是这样的。我正在检查是否有 token 以及何时将其附加到 header ,然后我使用 vue-resource post 方法发出 post 请求。
let headers = new Headers({'Content-Type': 'application/json;charset=utf-8'});
if(token !== '') {
headers.append('TOKEN', token);
}
return this.http.post(uri, data, headers)
.then(this.extractData)
.catch(this.handleError);
但这并不附加 TOKEN
这是什么作用
this.http.interceptors.push(function(request) {
request.headers.set('TOKEN', token);
});
在 headers.append('TOKEN', token); 的地方
但出于某种原因,它不是针对某些请求而是针对所有请求推送 TOKEN
header
因此,当我使用 token 发出请求时 - 它工作正常,之后我发出没有 token 的请求,但它仍然添加它。
谁知道解决这个问题的最佳方法是什么?
UPD 如果我 console.log(headers.get('TOKEN'))
在执行 headers.append('TOKEN', token);
它给了我正确的值。所以我的猜测是 post 请求本身是用错误的 header 调用的。
最佳答案
在document , headers
应该是普通的 Javascript 对象,而不是 window.Headers
请试试
let headers = {
'Content-Type': 'application/json;charset=utf-8'
};
if(token !== '') {
headers['TOKEN'] = token
}
return this.http.post(uri, data, {headers})
.then(this.extractData)
.catch(this.handleError);
关于vue.js - 如何添加额外的 header 以使用 vue-resource 发布请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51666276/