expressjsHow do I use Express.js to get a user's IP address?
Using Express.js to get a user's IP address is very simple. The following example will show how to do this:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
const ip = req.ip
console.log(ip)
res.send(ip)
})
app.listen(3000, () => console.log('Listening on port 3000'))
In the example above, the req object is used to get the user's IP address. The req.ip property returns the user's IP address as a string. The IP address is then printed out to the console and sent as a response to the user.
Code explanation
const express = require('express'): imports the Express.js module.const app = express(): creates an instance of the Express.js application.app.get('/', (req, res) => { ... }): defines a route handler for theGETrequest to the/route.const ip = req.ip: gets the user's IP address from thereqobject.console.log(ip): prints the IP address to the console.res.send(ip): sends the IP address as a response to the user.app.listen(3000, () => console.log('Listening on port 3000')): starts the Express.js server on port 3000.
The output of the example code will be the user's IP address printed out to the console.
Helpful links
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- How do I download a zip file using Express.js?
- How do I use Express.js to parse YAML files?
- How can I disable the X-Powered-By header in Express.js?
- How can I use the x-forwarded-for header in Express.js?
- How do I implement CSRF protection in an Express.js application?
- How do I use Yarn to add Express.js to my project?
- How do Express.js and Spring Boot compare in terms of features and performance?
- How can I use Express.js and Vite together for software development?
- How can I create and use models in Express.js?
See more codes...