I have an app that was written in jQuery. I'm trying to modernize it. As part of that, I'm trying to convert a jQuery request to Axios. My jQuery request looks like this:
var myUrl = '[someUrl]';
var myData = {
firstName: 'Joe',
lastName: 'Smith'
};
$.ajax({
type: 'POST', url: myUrl, cache: 'false',
contentType:'application/json',
headers: {
'Content-Type': 'application/json',
'key': '12345'
},
data: JSON.stringify(myData),
success: onSearchSuccess,
error: onSearchFailure,
complete: onSearchComplete
});
Now, with my modern code, I have the following:
var myUrl = '[someUrl]';
var myData = {
firstName: 'Joe',
lastName: 'Smith'
};
axios.post(myUrl, myData)
.then(function (response) {
alert('yeah!');
console.log(response);
})
.catch(function (error) {
alert('oops');
console.log(error);
})
;
I'm not sure how to pass in the headers or if I need to stringify myData
. Can someone please point me in the right direction?
Have you tried the manual? :)
Here's what you need:
axios.post(url[, data[, config]])
The way you translate that into code is:
var myUrl = '[someUrl]';
var myData = {
firstName: 'Joe',
lastName: 'Smith'
};
axios.post(myUrl, myData, {
headers: {
'Content-Type': 'application/json',
'key': '12345'
}
// other configuration there
})
.then(function (response) {
alert('yeah!');
console.log(response);
})
.catch(function (error) {
alert('oops');
console.log(error);
})
;
The returned object implements the A+ Promise API. Based on your configuration you may need to polyfill that, but there are a lot of packages available on in the npm registry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With