
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Express.js – req.ip Property
req.ip consists of the remote IP address from where the request is received. The value of this property is taken from the leftmost entry in the x-forwarded-for header when the trust proxy settings are not set to False. The headers are set by the client or proxy.
Syntax
req.ip
Example 1
Create a file with the name "reqIp.js" and copy the following code snippet. After creating the file, use the command "node reqIp.js" to run this code as shown in the example below −
// req.ip Property Demo Example // Importing the express & cookieParser module var cookieParser = require('cookie-parser'); var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // Defining an Endpoint app.get('/api', function (req, res) { console.log("IP : ", req.ip); res.send(req.ip); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
Hit the following Endpoint with a GET request: localhost:3000/api
C:\home
ode>> node reqIp.js Server listening on PORT 3000 IP : ::ffff:127.0.0.1
Example 2
Let's take a look at one more example.
// req.ip Property Demo Example // Importing the express & cookieParser module var cookieParser = require('cookie-parser'); var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // Enabling trust proxy app.enable('trust proxy') // Defining an Endpoint app.get('/api', function (req, res) { console.log("IP : ", req.ip); res.send(req.ip); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
Hit the following Endpoints one by one −
GET Request – localhost:3000/api
and set the following header as −
x-forwarded-header – 103.0.113.165
C:\home
ode>> node reqIp.js Server listening on PORT 3000 IP : 103.0.113.165
Advertisements