2017-04-05 60 views
5

去除报头字段当我实例化一个Vuejs (2.2.6)和Vue的资源(1.2.1),我设置用下面的代码的标题授权,这种方式我可以授权给我的API的所有请求:VueJs和VueResource,从Ajax请求

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

这样的授权字段与所述头中发送,上访问控制请求报头

Request header

我试图删除一些报头字段用以下代码,没有成功。

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

有没有办法从给定的请求删除授权场,或任何其他方面?
谢谢。

*更新*

通过使用拦截器(如下面的示例中)我可以编辑我无法删除特定字段的请求,但

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

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

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

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

editing request

尝试删除:

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

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

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

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

enter image description here

回答

7

使用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(); 
}); 
+0

这是令人难以置信的,我可以设置/修改,但我不能删除! –

+1

@ThiagoPereira我认为这可能是因为你将它们分配给'.common'。你能不*做到这一点,只是像上面那样分配它们? – Bert

+0

拦截器内部的'request.headers.common'是'undefined',我使用你的例子,当我尝试删除这个记号时什么都没有发生。请参阅上面的照片。你认为这是错误的:'Vue.http.headers.common.AUTHORIZATION ='持票人:...';' –