'How Can I Use the GET Method to Obtain a User's IP Address in Pure JS?
Hello this is my first question here. I'm really new to JS and i need a pure JS way to get the IP address of a web visitor and display it to him. How can i do it using GET and does anybody know why my code below will not work?
My aim is to get the info from http://ip-api.com/json
function goHome () {
var xhr = XMLHttpRequest();
xhr.open("GET", "http://ip-api.com/json", false);
xhr.send();
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.query);
}
}
Solution 1:[1]
This solution doesn't make use of the GET method but instead uses the fetch one - solution in pure js. I hope it helps ! Cheers!
<!DOCTYPE html>
<html>
<head>
<title>Get user's IP</title>
<style>
body{
background-color: black;
}
p, h1 {
color: white;
font-family: courier;
}
</style>
<script>
function json(url) {
return fetch(url).then(res => res.json());
}
json(`https://api.ipify.org?format=json`).then(data => {
console.log(data.ip);
document.getElementById('userip').innerHTML = data.ip;
});
</script>
</head>
<body>
<p style="text-align:center;font-size: 3em" id="userip"></p>
</body>
</html>
EDIT
It works if you also use this api: http://ip-api.com/json but you have to change data.ip => data.query - on stackoverflow the request gets blocked so i used the ipify.org api.
Solution 2:[2]
var xhr = XMLHttpRequest();
XMLHttpRequest is a constructor function, you must call it with the new operator - like the example below:
var xhr = new XMLHttpRequest();
Solution 3:[3]
This is an function with an async response. The easiest way to implement is using callbacks:
function goHome(cb){
var xhr = new XMLHttpRequest();
var fnError = function(type){
return function(){
console.error('error', type, 'has ocurred');
cb({error: type});
};
};
var fnOK = function(evt){
if (evt.currentTarget && evt.currentTarget.readyState === 4 && evt.currentTarget.status === 200) {
try{
var response = JSON.parse(evt.currentTarget.responseText);
cb(null, response.query)
}catch(err){
fnError('parsing xhr failed')();
}
} else {
fnError('xhr failed')();
}
}
xhr.open("GET", 'http://ip-api.com/json', true);
xhr.addEventListener('error', fnError('error') );
xhr.addEventListener('abort', fnError('abort') );
xhr.addEventListener('load', fnOK);
xhr.send();
}
basic usage:
goHome(function(err, ip){
if (err){
console.error(err);
} else {
//do stuff
console.log(JSON.stringify(ip));
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
