I am trying to make an axios call in my code to get a csv file and convert it to JSON. I am able to make the call and conversion correctly when the code stands on its own, but when I change it to be called as a function from an external source, I get an error code 400 when the axios call is executed, but then I get a correct response with status 200 anyway. This is the code I am executing as a test:
console.log('Test1');
getCSVUsers(usersurl, user, pass, CSVdelimiter)
.then((usersjson) => {
console.log(usersjson.users[0]);
})
And the definition of the function:
//Dependencies
import axios from 'axios';
import csv from 'csvtojson';
const getCSVUsers = (url,user,pass,delimiter) => {
console.log('Test3')
return new Promise((resolve, reject) => {
console.log('Test4');
let users = {}; //Creating JSON structure
users.users = []; //Creating required array in users JSON.
const options = { //Creating GET call credentials requirements
method: 'post',
headers: {
'Authorization': 'Basic '+Buffer.from(`${user}:${pass}`).toString('base64')
}
}
console.log('Test5');
//Make API get call
axios.get(url, options) //Making the call
.then(response => { //Getting the response
console.log('response.status');
csv({
delimiter: delimiter, //Defining the CSV delimiter
trim:true
})
.fromString(response.data) //Processing CSV from response
.then(function(jsonArrayObj){ //putting result in object
users.users = jsonArrayObj; //putting object in json array
resolve(users);
})
}).catch((err) => {
console.log('TestErr');
console.error(err);
});
});
}
export {getCSVUsers}
The console returns the following:
Test1
Test3
Test4
Test5
Response Error:Error: Request failed with status code 400
200
{User1 stats are returned correctly}
I tried making the function async and adding "await", but that didn't solve the issue either.