Axios: Basic auth not working with GET request

Viewed 8097

I have axios get request with basic auth, but i keep getting back a 401 status code. My code does work if i am doing a post request, so I don't know what i'm doing wrong here.

My backend code:

app.get('/api/find-user', (req, res) => {
    const username = req.body.username;
    axios.get('my-url', username, {
        auth:{
            username: 'my-username',
            password: 'my-password'
        }
    })
    .then(resp => {
        res.json({resp});
    })
    .catch(error => {
        res.send(error.response.status);
    })
});

My frontend code:

findUser(user){
    const username = user;
    axios.get('/api/find-user', {username})
        .then(resp => {
            console.log(resp);
        })
        .catch(error => {
            console.log(error)
        })
}

Again when i am doing a post to create a new user it does work, but when i am doing a GET request it keeps saying i am not authorized.

Edit: If you feel like downvoting be adult enough to explain why.

2 Answers

You need to do:

const usernamePasswordBuffer = Buffer.from(username + ':' + password);
const base64data = usernamePasswordBuffer.toString('base64');
const axiosObject = axios.create({
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${base64data}`,
    }
});

Because Axios needs the auth to be "encrypted" with both username and password.

There’s quite a few potential causes here. I think it might be helpful to state which API you’re trying to access. For instance:

  • do you definitely have READ access granted for your account on the API server?
  • your POST request isn’t using a password so is your password definitely correct for the GET?
Related