0

I want to change jQuery api call to axios api call.

jQuery code is below

$.getJSON('some_url?CART_GOODS_INFO=' + encodeURIComponent(cartData) + '&callback=?', function (data) {
            if (data.IsSuccess) {
                alert('success');
           } else {
                if ($.trim(data.ResultMessage) != '') {
                    alert(data.ResultMessage);
                } else {
                    alert('failed');
                }
            }
        });

I've tried to change this code in to axios

axios.get('some_url', {
        params: {
            CART_GOODS_INFO: encodeURIComponent(cartData)
        }
      })
      .then((response) => {
        console.log(response)
      })
      .catch((error) => {
        console.log(error)
      })
      .then(() => {
        // always executed
      })

I am getting CORS error which has nothing to do with my question.

Anyways, does this seem to be the right code from 'jQuery getJSON' to 'axios get'?

I am not quite sure what that '&callback=?' in jQuery code.

FYI. that some_url is not the actual url. just in case if you are confused.

Anybody has any ideas, please add comment. Thanks in advance.

LeeMinHo
  • 298
  • 1
  • 3
  • 10

1 Answers1

0

You are getting CORS error with axios but not with jQuery.

CORS error means your server does not have an Allow access control origin header present in response. Since browsers do not allow cross-domain calls by default, you are getting this error.

In earlier days, JSONP was used as a workaround to this problem. A callback is sent in request and the server sends the responds by wrapping the response in callback function. This is what your jQuery code is doing. Read more about it here.

To solve this, you will have to figure a way to make JSONP calls with axios.

Hope it helps.

Vijay Joshi
  • 919
  • 7
  • 17