Convert jQuery query to Axios

I have an application written in jQuery. I am trying to upgrade it. As part of this, I am trying to convert a jQuery query 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 go through the headers or I need to execute string myData

. Can anyone point me in the right direction?

+3


source to share


1 answer


Have you tried the guide ? :)

Here's what you need:

axios.post (url [, data [, config]])



How do you translate code into code:

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 . You may need a polyfill based on your configuration, but there are many packages in the npm registry.

+3


source







All Articles