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 theGET
request to the/
route.const ip = req.ip
: gets the user's IP address from thereq
object.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 set up a YAML configuration file for a Node.js Express application?
- How can I use express-zip js to zip and download files?
- How do I download a zip file using Express.js?
- How do I implement CSRF protection in an Express.js application?
- How can I disable the X-Powered-By header in Express.js?
- How can I use Express.js and Nest.js together to create a web application?
- How can I use Express.js to prevent XSS attacks?
- How do I use adm-zip with Express.js?
- How do I set the time zone in Express.js?
- How do I use Express.js to parse YAML files?
See more codes...