Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting jQuery Request to Axios

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?

like image 316
Gary Avatar asked Apr 03 '17 19:04

Gary


1 Answers

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.

like image 63
motanelu Avatar answered Nov 17 '22 12:11

motanelu