Reputation: 1051
so far I've been using request-promise which is now deprecated. I have chosen axios to be the successor and I adapted the code but unfortunately I keep getting error 401 "Unauthorized". It seems as if axios is not passing the auth info given. My old source code looks like this:
let options = {
method: 'GET',
uri: 'https://example.com/bla',
auth: {
user: 'USER',
pass: 'PASSWORD',
sendImmediately: true
},
headers: {
'X-CSRF-Token': 'Fetch'
},
resolveWithFullResponse: true
};
let rpWithDefaults = rp.defaults({
rejectUnauthorized: false,
jar: true
});
let response = await rpWithDefaults(options);
The adapted code snippet looks like this:
const axios = require('axios').default;
const https = require('https');
const response = await axios({
method: 'GET',
url: 'https://example.com/bla',
headers: {
'X-CSRF-Token': 'Fetch'
},
httpsAgent: new https.Agent({
rejectUnauthorized: false,
auth: {
user: 'USER',
pass: 'PASSWORD'
}
}),
resolveWithFullResponse: true
});
What am I doing wrong?
Thanks
Upvotes: 0
Views: 1229
Reputation: 1051
Axios doc says you need to pass this way.
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
// Please note that only HTTP Basic auth is configurable through this parameter.
// For Bearer tokens and such, use `Authorization` custom headers instead.
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
So did you try just changing the key from user
and pass
to username
and password
const axios = require('axios').default;
const https = require('https');
const response = await axios({
method: 'GET',
url: 'https://example.com/bla',
headers: {
'X-CSRF-Token': 'Fetch'
},
auth: {
username: '<user-name>',
password: '<password>'
},
resolveWithFullResponse: true
});
Upvotes: 3
Reputation: 31
I've not used the httpsAgent
parameter before, but I don't think it's required to make https calls in Axios. Does the following work for you?
const axios = require('axios').default;
const response = await axios({
method: 'GET',
baseURL: 'https://example.com/',
url: '/bla',
headers: {
'X-CSRF-Token': 'Fetch'
},
auth: {
user: 'USER',
pass: 'PASSWORD'
}
});
Maybe relevant: reactjs make https (not http) requests with axios
Upvotes: 0