繁体   English   中英

如何使用React在客户端上向外部站点发出AJAX GET请求

[英]How to make AJAX GET request on the client to external site with React

您好我是React的新手,我正在尝试向外部API发出AJAX GET请求。 但是,我添加的URL将在我的主机前面添加。 如果我正在做些什么,请告诉我。 以下是我的代码。

$.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请求将发送到localhost:3000/http://www.someapi.com/?i=1

当您尝试从不同的域获取json存在安全问题,因此默认行为不允许它,但您可以使用jsonp作为解决方法。

以下是包含jsonp GET请求的修改版本。 添加是指定jsonp返回类型和回调函数名称。

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

您应该查看有关跨域请求的这些答案。

jQuery AJAX跨域

使用jQuery AJAX加载跨域端点

它可能会引导您找到正确的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM