简体   繁体   中英

Get client ip address from fetch response

Is it possible to get the client Ip address from the response of ta fetch? Something like this

  fetch(url)
    .then((response) => {
      console.log("My IP Address: ", response.originIP);
    })

That is not possible. All the available methods of the fetch response are listed here: https://developer.mozilla.org/en-US/docs/Web/API/Response

You could however create a web service to return an IP address: How to get client's IP address using JavaScript?

If what you want is to just get your client's public IP address, use this:

async function getClientIp() {
    const { ip } = await fetch('https://api.ipify.org?format=json', { method: 'GET' })
        .then(res => res.json())
        .catch(error => console.error(error));
    
    return ip ?? "Unknown";
}

To know more about fetch : here .

To know more about ipify : here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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