VueJs and VueResource by removing header fields from an Ajax request

When I create an instance of Vuejs (2.2.6) and a Vue resource (1.2.1) , I set the header authorization with the following code, so I can resolve all requests to my API:

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

However, I want to make a request for a third-party API, and I do not want the Authorization field to be sent. In addition, this API does not allow the use of this authorization header.

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

Thus, the authorization field is sent with a header in the Access-Control-Request-Headers :

Request header

I tried to remove some header fields with the following codes without success.

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

The vue-resource documentation has the ability to insert an object to force the request, but the documentation is not complete.

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

Is it possible to remove an authorization field or any other field from a given request?
Thanks.

* UPDATED *

Using interceptors (as in the example below) , I can edit the request, but I cannot delete a specific field.

 Vue.http.interceptors.push((request, next) => { const viacep = request.url.includes('viacep.com.br'); if (viacep) { request.headers.set('AUTHORIZATION', 'TRY THIS'); } next(response => {}); }); 

edit request

Try to delete:

 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

+5
source share
1 answer

Use an interceptor , check the request and remove the header, if necessary.

 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(); }); 
+7
source

Source: https://habr.com/ru/post/1266390/


All Articles