4

Hello I'm new to React and I am trying to make an AJAX GET request to an external API. However, the URL I add is being prepended with my host. Please let me know if I am doing something off. Below is my code.

$.ajax({
  type: 'GET',
  url: 'http://www.someapi.com/?i='+someId,
  async: false,
  dataType: 'json',
  success: function(data) {
    this.setState({data: data});
  }.bind(this),
  error: function(e) {
     console.log('error', e);
  }
});

The GET request is being sent to localhost:3000/http://www.someapi.com/?i=1

user522
  • 43
  • 1
  • 5

2 Answers2

3

When you are trying get json from a different domain there are security concerns, so the default behavior doesn't allow it, but you could use jsonp as a work around.

Below is the modified version of your GET request that incorporates jsonp. The addition is specifying jsonp return type and a callback function name.

    // If you are doing making this request multiple times the AJAX request
    // may fail due to the same callback name, so you could generate random    
    // callback names to get around it.
    var callback = 'c'+Math.floor((Math.random()*100000000)+1);

    $.ajax({
      type: 'GET',
      url: 'http://www.someapi.com/?i='+id,
      jsonpCallback: callback, //specify callback name
      contentType: 'application/json',
      dataType: 'jsonp', //specify jsonp
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(e) {
         console.log('error', e);
      }
    });
FullStack
  • 5,902
  • 4
  • 43
  • 77
  • 1
    Glad I could help! Also look into [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) as a more secure way. – FullStack Jul 13 '15 at 16:26
0

You should check out these answers about cross-domain requests.

jQuery AJAX cross domain

Loading cross domain endpoint with jQuery AJAX

It may lead you to the correct answer.

Community
  • 1
  • 1
Jeremy
  • 51
  • 1
  • 4