如何从reactjs组件发出跨域请求?

时间:2017-11-04 06:46:01

标签: jquery reactjs axios

我有一个reactjs组件,并且我想在其中一个方法中提出ajax请求:

$.ajax({
         type: 'GET',
         crossDomain: true,
         url:'http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1',
         success: (res) => {},
         error: (fail) => {}
      })

当我加载组件时,请求无法加载并显示错误:

  

请求的资源上没有“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:8080”访问。

是否可以解决此问题,还是应该采用不同的方法?

1 个答案:

答案 0 :(得分:0)

制作跨域请求你应该使用jsonp或者反向代理

    $.ajax({
    url:"http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1",
    type:"GET",
    jsonpCallback: "getStatus",
    dataType: "jsonp",

});
function getStatus(response)
{
    console.log(response);
}