如何使用 vue-resource 添加额外的 header 到 post 请求?

How to add extra header to post request with vue-resource?

我的应用中有许多 post 请求。其中一些必须使用 token 并提取 header 我不确定如何附加它

到目前为止我的代码是这样的。我正在检查是否有令牌,何时将其附加到 headers,然后我使用 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 不是针对某些请求而是针对所有请求

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

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

UPD 如果我在执行 headers.append('TOKEN', token);console.log(headers.get('TOKEN')) 它会给我正确的值。所以我的猜测是 post 请求本身被错误地调用 headers.

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

好的,我想我明白了。感谢@ssc-hrep3 的评论和@ittus

的回答
let headers = {
        'Content-Type': 'application/json;charset=utf-8'
      };

      if(token !== '') {
        headers['TOKEN'] = token
      }

      return this.http.post(uri, data, {headers: headers})
             .then(this.extractData)
             .catch(this.handleError);
Vue.http.headers.common['Authorization'] = "Basic Token";