How to make an AJAX GET request to a client on an external site using React

Hello, I'm new to React, and I'm trying to make an AJAX GET request an external API. However, the added URL is added to my host. Please let me know if I am doing something. 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);
  }
});

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

+4
source share
2 answers

When you try to get jsonfrom another domain, there are security problems, so the default behavior does not allow this, but you can use it jsonpas work.

Below is a modified version of your GET request, including jsonp. The appendix indicates the type of the return type jsonpand the name of the callback function.

    // 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);
      }
    });
+3

All Articles