Created
January 15, 2024 02:22
-
-
Save anishjoshi1999/7c39f336b680fde03411bc28ca35eef2 to your computer and use it in GitHub Desktop.
How to Find the IP Address of Your Computer Using Express.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require("http"); | |
const trackVisitsMiddleware = async (req, res, next) => { | |
// Obtain the public IP address from api.ipify.org | |
const api = { | |
host: "api.ipify.org", | |
port: 80, | |
path: "/", | |
}; | |
try { | |
const responseData = await fetchData(api); | |
const ipAddress = responseData.trim(); | |
console.log(`Here is your IP Address: ${ipAddress}`) | |
} catch (error) { | |
console.error("Error fetching data:", error); | |
} | |
next(); | |
}; | |
const fetchData = async (api) => { | |
return new Promise((resolve, reject) => { | |
const req = http.get(api, (response) => { | |
let data = ""; | |
response.on("data", (chunk) => { | |
data += chunk; | |
}); | |
response.on("end", () => { | |
resolve(data); | |
}); | |
}); | |
req.on("error", (error) => { | |
reject(error); | |
}); | |
req.end(); | |
}); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment