What will be the value of req.ip when a client makes a request to an Express server running locally?
app.get('/', (req, res) => {
res.send(req.ip);
});Think about how IPv6 localhost address is represented.
When running locally, Express sets req.ip to the client's IP address. For localhost, this is usually the IPv6 loopback address ::1.
If a client accesses an Express app via http://myapp.example.com, what will req.hostname return?
app.get('/', (req, res) => {
res.send(req.hostname);
});Consider what part of the URL req.hostname extracts.
req.hostname returns the hostname from the Host HTTP header, which includes subdomains like myapp.example.com.
What happens when executing this code to get the client's IP address in Express?
app.get('/', (req, res) => {
const clientIp = req.ipAddress;
res.send(clientIp);
});Check what happens when accessing a non-existent property on an object.
req.ipAddress does not exist. Accessing it returns undefined without error. The correct property is req.ip.
What will req.hostname return if the client sends a request with the Host header set to myapp.example.com:3000?
app.get('/', (req, res) => {
res.send(req.hostname);
});Remember how Express parses the Host header for hostname.
req.hostname excludes the port number and returns only the hostname part of the Host header.
An Express app is behind a proxy. The developer notices req.ip always shows the proxy's IP, not the client's. What is the correct fix?
app.set('trust proxy', false); app.get('/', (req, res) => { res.send(req.ip); });
Express needs to trust the proxy to get the real client IP.
Setting trust proxy to true tells Express to use the X-Forwarded-For header to get the real client IP behind proxies.