【问题标题】:VueJs and VueResource, removing header fields from a Ajax requestVueJs 和 VueResource,从 Ajax 请求中删除标头字段
【发布时间】:2017-08-31 17:58:51
【问题描述】:

当我实例化一个 Vuejs (2.2.6) 和 Vue-resource (1.2.1) 时,我使用以下代码设置标题授权,这样我可以授权对我的 API 的所有请求:

Vue.http.headers.common.AUTHORIZATION = 'BEARER ...';

但是,我想请求第三方 API,并且我不希望发送 Authorization 字段。此外,此 API 不允许您使用此授权标头。

let CEP = '';

this.$http.get('https://viacep.com.br/ws/' + CEP + '/json')
    .then(response => {
        console.log(response.headers);
    });

这样,授权字段与标头一起发送,在 Access-Control-Request-Headers 上:

我尝试使用以下代码删除一些标题字段,但没有成功。

this.$http.headers.common.AUTHORIZATION = null;
this.$http.headers.common['Access-Control-Allow-Headers'] = null;

this.$http.get('https://viacep.com.br/ws/' + CEP + '/json')
    .then(response => {
        console.log(response.headers);
    });

vue-resource 文档中,有可能插入一个对象来强制请求配置,但文档并不完整。

this.$http.get('https://viacep.com.br/ws/' + CEP + '/json', {
   ...here...
}).then(response => {
    console.log(response.headers);
});

有没有办法从给定的请求中删除 Authorization 字段或任何其他字段?
谢谢。

* 已更新 *

通过使用拦截器(如下例所示)我可以编辑请求,但我不能删除特定字段。

Vue.http.interceptors.push((request, next) => {

    const viacep = request.url.includes('viacep.com.br');

    if (viacep) {
        request.headers.set('AUTHORIZATION', 'TRY THIS');
    }

    next(response => {});
});

尝试删除:

Vue.http.interceptors.push((request, next) => {

    const viacep = request.url.includes('viacep.com.br');

    if (viacep) {
        request.headers.delete('AUTHORIZATION');
    }

    next(response => {});
});

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-resource


    【解决方案1】:

    使用interceptor,检查请求,并在需要时删除标头。

    Vue.http.interceptors.push(function(request, next) {
    
      const removeAuthHeaders = request.url.includes("viacep.com.br");
    
      if (removeAuthHeaders){
        request.headers.delete('Access-Control-Allow-Headers')
        request.headers.delete('AUTHORIZATION')
      }
      else {
        request.headers.set('Access-Control-Allow-Headers', <value>)
        request.headers.set('AUTHORIZATION', <value>)
      }
      next();
    });
    

    【讨论】:

    • 难以置信,我可以设置/修改却不能删除!
    • @ThiagoPereira 我认为这可能是因为您将它们分配给了.common。你能那样做,像我上面那样分配它们吗?
    • 拦截器内部的request.headers.commonundefined,我使用的是你的例子,当我尝试删除令牌时没有任何反应。请看上面的印刷品。你认为这是错误的:Vue.http.headers.common.AUTHORIZATION = 'Bearer: ...';
    • @ThiagoPereira 我想说的是,如果你在某处运行过这条线,Vue.http.headers.common.Authorization = &lt;whatever&gt;,那么它不能被删除。如果你那样做,只是在需要时在拦截器中添加授权头only,那么你应该没问题。
    猜你喜欢
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2020-09-08
    • 1970-01-01
    • 2012-01-19
    • 2015-03-28
    • 2015-01-20
    相关资源
    最近更新 更多