I am implementing an API which is based on POST method. Now, I have tried axios as well as fetch (promise) method but I am constantly having this error of "401 Authentication Failed".
- For testing, I defined the data values to be sent into this.state as default values.
- apiKey and userId are defined as var outside the React.Component.
- Instead of using inbuilt btoa function, I am using the one from npm directory which is imported on the top.
Here is the React Component code:-
constructor(props) {
super(props);
this.state = {
day: 1,
month: 2,
year: 2019,
hours: 12,
minutes: 59,
tzone: 5.5,
lat: 19.22,
lon: 25.2
};
}
componentDidMount() {
const options = {
headers: {
"Authorization": "Basic" + btoa(userId+":"+apiKey),
"Content-Type":'application/json'
}
};
const url = `https://json.astrologyapi.com/v1/current_vdasha`
const data = this.state
fetch(url, { method: 'POST',
body: JSON.stringify(data),
headers: options })
.then(res => res.json())
.catch(error => console.error('error ---', error.message))
.then(response => console.log('Success:', response));
}
Any help is appreciated. Thank you.
var userId = ''; var apiKey = ''; var data = 'JSON Request Data'; var request = $.ajax({ url: "https://json.astrologyapi.com/v1/"+api, method: "POST", dataType:'json', headers: { "authorization": "Basic " + btoa(userId+":"+apiKey), "Content-Type":'application/json' }, data:JSON.stringify(data) }); // Returns A promiss return( request.then( function(resp){ return resp; }, function(err){ return err; })); }