0
0
Expressframework~15 mins

req.ip and req.hostname in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Using req.ip and req.hostname in Express
📖 Scenario: You are building a simple Express server that logs and shows the visitor's IP address and the hostname they used to access your site. This helps you understand where your visitors come from and which domain they used.
🎯 Goal: Create an Express server with a route that reads the visitor's IP address using req.ip and the hostname using req.hostname. Then send a response showing these values.
📋 What You'll Learn
Create an Express app
Add a route for GET requests to '/'
Use req.ip to get the visitor's IP address
Use req.hostname to get the hostname
Send a response that includes both the IP and hostname
💡 Why This Matters
🌍 Real World
Web servers often need to know the visitor's IP and hostname to customize responses, log traffic, or apply security rules.
💼 Career
Understanding how to access request details like IP and hostname is essential for backend developers working with Express or similar web frameworks.
Progress0 / 4 steps
1
Set up Express app
Create a variable called express by requiring the 'express' module. Then create a variable called app by calling express().
Express
Need a hint?

Use require('express') to import Express and then call it to create your app.

2
Add a GET route for '/'
Add a GET route on app for path '/' with a callback function that takes req and res as parameters.
Express
Need a hint?

Use app.get with the path '/' and a function with req and res.

3
Get visitor IP and hostname
Inside the GET route callback, create two variables: visitorIp set to req.ip and visitorHost set to req.hostname.
Express
Need a hint?

Use req.ip to get the IP and req.hostname to get the hostname.

4
Send response with IP and hostname
Still inside the GET route callback, send a response using res.send that includes the text: `Your IP is ${visitorIp} and your hostname is ${visitorHost}`.
Express
Need a hint?

Use a template string inside res.send to include the variables.