Ipify被CORS阻止了,我该如何允许它?

9

我正在尝试在我的网站上添加代码以获取用户的IP地址。我正在使用带有axios的react(mobx/mst)。

   getIpAddress: flow(function*() {

    const response = yield axios.get('http://api.ipify.org/?format=text');
    self.ipAddress = response.data;  

    })

Access to XMLHttpRequest at 'http://api.ipify.org/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
1个回答

15

这是典型的CORS问题。服务器不允许您的客户端直接获取信息。您应该使用一些服务器端代理或使用https://cors-anywhere.herokuapp.com/,这样您的代码将如下所示。

getIpAddress: flow(function*() {
  const response = yield axios.get('https://cors-anywhere.herokuapp.com/http://api.ipify.org/?format=text');
  self.ipAddress = response.data;  
})

抱歉,你的代码看起来和我的代码很像?你添加了什么?我也不理解Jquery ajax是如何工作的(这是他们的一个例子:https://www.ipify.org/),但axios却可以。 - chobo2
抱歉,我刚刚编辑了我的答案,请再次检查。 - viciousP
好的,我会检查一下,只是根据他们列出如何使用jquery ajax获取ip的示例,所以我认为它应该可以工作。 - chobo2
1
我能否使用cors-anywhere获取客户端的IP地址?它似乎是运行cors-anywhere应用程序的服务器的IP地址。 - wafe
2
当我们通过代理时,我想知道我们获取的是服务器还是客户端的IP地址... - TienPing
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接