'401 Unauthorized error when making axios request
I am using axios to make different GET and POST requests to a third-party API that requires a username and password login to access the data. I have tried several approaches to make this work but I keep getting this error in the console.
data: '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n' +
'<html><head>\n' +
'<title>401 Unauthorized</title>\n' +
'</head><body>\n' +
'<h1>Unauthorized</h1>\n' +
'<p>This server could not verify that you\n' +
'are authorized to access the document\n' +
'requested. Either you supplied the wrong\n' +
'credentials (e.g., bad password), or your\n' +
"browser doesn't understand how to supply\n" +
'the credentials required.</p>\n' +
'</body></html>\n'
}
I have been using this approach to send the username and password with node.js
export const getCameraStream = (req, res) => {
let conn = createConnection(config);
let query = `SELECT * FROM cameras WHERE id = ${req.params.id}`
conn.connect();
conn.query(query, async (error, rows, _) => {
const camera = rows[0];
const username = camera.user;
const password = camera.pass;
if (error) {
return res.json({ "status": "failure", "error": error });
}
const result = await axios({
method: 'get',
url: <placeholder for api url>,
auth: {
username, password
}
})
console.log(result);
});
conn.end();
}
and then use this code on my React front-end
const getCameraStream = async () => {
const username = camera.user
const password = camera.pass
try {
const token = Buffer.from(`${username}:${password}`).toString('base64')
const res = await publicRequest.get(`camera/getCameraStream/${camera.id}`, {
headers: {
'content-type': 'multipart/x-mixed-replace; boundary=--myboundary',
'Authorization': `Basic ${token}`
},
auth: {
username, password
}
})
console.log(res)
} catch (error) {
console.error(error)
}
}
Using this approach, I am able to pass the username and password to the server and the responseUrl property is correct. However, my app crashes and I keep getting the same unauthorized error in the console. Could this be an issue with the fact that the browser is sending a preflight OPTIONS request or am I overlooking something with my authorization?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
