Ipify Getting Blocked By Cors. How do I get it be allowed?

cho*_*bo2 3 javascript cors reactjs axios

I am tyring to add code to get the ipaddress of the user on my site. I am using a react(mobx/mst) with axios.

   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
Run Code Online (Sandbox Code Playgroud)

vic*_*usP 5

这是典型的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;  
})
Run Code Online (Sandbox Code Playgroud)

  • 我想知道当我们通过代理时我们是否获得服务器或客户端的IP地址...... (2认同)