- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Getting the Domain Info for Request in Express.js
We need to get the DNS information to track the address from where we receive the requests. This feature also provides an added layer of security, protecting the application from different type of DOS and DDOS attacks.
We can use the following functions to get the domain and host information.
Syntax
Getting the origin info:
var origin = req.get('origin');
Getting the host info:
var host = req.get('host');
Example 1
Create a file with the name "dnsInfo.js" and copy the following code snippet. After creating the file, use the command "node dnsInfo.js" to run this code as shown in the example below −
// Getting the Host info Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); var PORT = 3000; // Creating a GET Api endpoint app.get("/route", (req, res) => { var host = req.get('host'); console.log(host) var origin = req.get('origin'); console.log(origin) }) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
Hit the following URL with a GET request: localhost:3000/route
C:\home
ode>> node dnsInfo.js Server listening on PORT 3000 localhost:3000 undefined
Example 2
Let's take a look at one more example.
// Getting the Host info Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); var PORT = 3000; // Creating a GET Api endpoint app.get("/route", (req, res) => { var host = req.get('host'); console.log("Host: ", host) var origin = req.get('origin'); console.log("Origin: ", origin) var userIP = req.socket.remoteAddress; console.log("UserIp: ", userIP) res.send("DNS host" + host +" origin: " + origin +" userIP : "+ userIP) }) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
C:\home
ode>> node dnsInfo.js Server listening on PORT 3000 Host: localhost:3000 Origin: undefined UserIp: ::ffff:127.0.0.1
Advertisements