Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJs and VueResource, removing header fields from a Ajax request

When I instantiate a Vuejs (2.2.6) and Vue-resource (1.2.1), I set the header authorization with the following code, this way I can authorize 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. Additionally, this API does not allow you to use this authorization header.

let CEP = '';

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

This way the authorization field is sent with the header, on 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);
    });

In the vue-resource documentation, there is the possibility of inserting an object to force the request configuration, but the documentation isn't complete.

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

Is there any way to remove the Authorization field, or any other field from a given request?
Thanks.

* UPDATED *

By using the interceptors (as in the below sample) I can edit the request but I can not delete a particular 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 => {});
});

editing 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

like image 927
Thiago Pereira Avatar asked Apr 05 '17 22:04

Thiago Pereira


1 Answers

Use an interceptor, inspect the request, and remove the header if needed.

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();
});
like image 193
Bert Avatar answered Nov 14 '22 22:11

Bert