Reputation: 752
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.
Upvotes: 5
Views: 26183
Reputation: 1
app.get("/basicAuth", async(req,res) =>{
try{
const jsObj = await axios.get("API_URL", {
auth: {
username: "username"
passowrd: "password"
},
});
Upvotes: 0
Reputation: 11
This worked pretty well for me
const response = await axios.get('url', {
auth: {
username: 'Jane',
password: 'doe'
},
});
const result = response.data;
Upvotes: 0
Reputation: 51
For GET request you don't have a data object. You need send your params in config like this:
axios.get('my-url', {
auth: {
username: 'my-username',
password: 'my-password'
},
params: { username }
})
Upvotes: 5
Reputation: 121
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.
Upvotes: 11
Reputation: 1442
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:
Upvotes: 0