Search code examples
javascriptreactjshttprequestaxiosajax-request

How to set username and password in axios get method header


I want to fetch some data from a server via axios in my react project. When i put the url on browser and hit enter browser ask me username and password and after that, i can see the json data. But i dont know how to set the password and username in axios header in a get method. I have searched it in many forums and pages,especially this link didin't help me: Sending axios get request with authorization header . So finally i tried (many things before this, but i was more confused):

componentDidMount() {
   axios.get('http://my_url/api/stb', {auth: {
    username: 'usrnm',
    password: 'pswrd'
}})
   .then(function(response) {
       console.log(response.data);
       console.log(response.headers['Authorization']);
   }).catch(err => console.log(err));
}

And i can not get anything. I get this error in console:

Error: Network Error
Stack trace:
createError@http://localhost:3000/static/js/bundle.js:2195:15
handleError@http://localhost:3000/static/js/bundle.js:1724:14

Actually, the api documentation mentioned that with these words:

If there is no header or not correct data - server's answer will contain HTTP status 401 Unauthorized and message:

< {"status":"ERROR","results":"","error":"401 Unauthorized request"}

For successful authentification is sufficient to add in every request header to the API:

Authorization: Basic <base64encode("login":"password")>

The weird thing is, when i use postman, the response send me a "401 unauthorized" response below the body section. But i can not see any 401 errors in browser's console.


Solution

  • Ok i found the solution. As i mentioned in the comments that i wrote for my question, there was a cors problem also. And i figured out that cors problem was appearing because of that i can not authorize correctly. So cors is a nature result of my question. Whatever.. I want to share my solution and i hope it helps another people because i couldent find a clear authorization example with react and axios.

    I installed base-64 library via npm and:

    componentDidMount() {
            const tok = 'my_username:my_password';
            const hash = Base64.encode(tok);
            const Basic = 'Basic ' + hash;
           axios.get('http://my_url/api/stb', {headers : { 'Authorization' : Basic }})
           .then(function(response) {
               console.log(response.data);
               console.log(response.headers['Authorization']);
           }).catch(err => console.log(err));
        }
    

    And dont forget to get Authorization in single quotes and dont struggle for hours like me :)