如何使用vue-resource添加额外的标头以发布请求?

All*_*lan 5 vue.js vue-resource

我的应用程序中有许多发帖请求。其中一些必须具有和额外的头,token我不确定如何附加它

到目前为止,我的代码是这样的。我正在检查是否有令牌,何时将其附加到标头,然后使用vue-resource 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);
Run Code Online (Sandbox Code Playgroud)

但这不附加 TOKEN

这是什么工作

this.http.interceptors.push(function(request) {
                request.headers.set('TOKEN', token);
            });
Run Code Online (Sandbox Code Playgroud)

在...的地方 headers.append('TOKEN', token);

但是由于某种原因,它TOKEN不是针对某些请求而是针对所有请求推送标头

因此,当我使用令牌发出请求时-它工作正常,之后我又发出了没有令牌的请求,但它仍然添加了令牌。

有谁知道解决此问题的最佳方法是什么?

UPD如果我console.log(headers.get('TOKEN'))在执行headers.append('TOKEN', token);此操作,则会为我提供正确的价值。因此,我猜测发布请求本身被错误的标题调用。

itt*_*tus 7

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);
Run Code Online (Sandbox Code Playgroud)