【问题标题】:How to add extra header to post request with vue-resource?如何使用 vue-resource 添加额外的标头来发布请求?
【发布时间】:2019-01-10 23:20:15
【问题描述】:

我的应用中有许多发帖请求。其中一些必须使用token 来提取标题我不知道如何附加它

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

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

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

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

【问题讨论】:

标签: vue.js vue-resource


【解决方案1】:

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

【讨论】:

  • 是的,刚刚试过。如果我 console.log 标头它们是正确的,但请求仍然没有它们。
  • 第三个参数是一个配置对象。那么它不应该将headers 作为其中的键吗?
【解决方案2】:

好吧,我想我明白了。感谢@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);

【讨论】:

    【解决方案3】:
    Vue.http.headers.common['Authorization'] = "Basic Token";
    

    【讨论】:

      猜你喜欢
      • 2017-12-27
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多