Error Defining Headers-Authorization on the return of data in Axios

0

I'm trying to set the headers - Authorization after a request via axios, this request returns the token that is generated on the server, in line 7 of the code below assign the token that is returned to insert in the headers in Authorization and after that redirect to the Home page of the system, at line 8. However headers Authorization is not being created.

Would anyone know how to signal where the error is and how do I create the headers - Authorization with the token that is successfully returned in .then, line 5?

1          data = {email: email, password: password};   
2          url = '/auth/token';     
3               
4          axios.post(url, simpleQueryString.stringify(data))       
5            .then(function(response) {         
6                if (response.status == 201) {          
7                    window.axios.defaults.headers.common['Authorization'] = response.data.token;           
8                    redirectPageHome(response.data['base_url']);
9                }          
10           })         
11           .catch(function(error) {           
12              console.log(error.response.data.error);         
13           })
    
asked by anonymous 25.09.2018 / 18:37

1 answer

1

Friend, I believe window.location.replace might be generating a new request. If you're using Chrome, check out the developer tools on the Network tab.

I believe the right one in this case is to store locally ( local storage ) :

data = {email: email, password: password};   
url = '/auth/token';     

axios.post(url, simpleQueryString.stringify(data))       
    .then(function(response) {         
        if (response.status == 201) {
            localStorage.setItem('token',response.data.token);
            redirectPageHome(response.data['base_url']);
        }          
    })         
    .catch(function(error) {           
        console.log(error.response.data.error);         
    })

And then right after you've added axios , verify the token's existence and set up the header. Example:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
    // exemplos retirados da documentacao do axios
    // https://github.com/axios/axios

    // opcao 1 - configurar globalmente
    var token = localStorage.getItem('token');
    if (token) {
        window.axios.defaults.headers.common['Authorization'] = token; 
    }

    // opcao 2 - configurar a cada requisicao
    axios.interceptors.request.use(function (config) {
        var token = localStorage.getItem('token');
        if (token) {
            config.headers['Authorization'] = token;
        }
        return config;
    });
</script>

I hope it helps.

    
25.09.2018 / 19:11