I try to make a GET request with axios and I always get 401. This happens only when I send the request from my react app.
axios.get('http://localhost:8080/vehicles', {
withCredentials: true,
auth: {
username: 'admin',
password: 'admin'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
Postman GET request with the same credentials and Basic Auth set, works.
If I simply type in my browser the url, a login box appears and with the same credentials, it works, I get what I want.
I tried with SuperAgent too:
Request.get("http://localhost:8080/vehicles")
.withCredentials()
.auth('admin', 'admin')
.then(response => {
return response.body
});
Still nothing.
I saw a question related to this one but no one answered it.
Can anyone point me to the right direction?
Thank you for reading.
The 401 error you are receiving suggests that there is an issue with the authentication. Since the same credentials work when you type the URL in the browser and when you use Postman, it is likely that the issue is with the way you are passing the credentials in your axios and SuperAgent requests.
One thing to note is that axios and SuperAgent use different methods to send authentication credentials. Axios uses HTTP basic authentication, while SuperAgent uses the Authorization header.
Here's an example of how you can modify your axios request to use HTTP basic authentication:
axios.get('http://localhost:8080/vehicles', { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, auth: { username: 'admin', password: 'admin' } })
Note that you do not need to set the withCredentials flag for HTTP basic authentication.
For SuperAgent, you can modify your request like this:
Request.get('http://localhost:8080/vehicles') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .auth('admin', 'admin') .then(response => { return response.body; });
Make sure that the username and password are correct and that they match the credentials that the server is expecting. Additionally, make sure that the server is configured to accept HTTP basic authentication.
If you are still having trouble, you may want to check the server logs for any error messages or consult the server's documentation for information on how to authenticate requests.