- 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
req.protocol Property in Express.js
The req.protocol property returns the request protocol string that is either http or (for TLS requests) https. The value of X-Forwarded-Proto header field is used if present, when the passed trust proxy setting does not evaluate to False. This header values can be set either by the client or by the proxy.
Syntax
req.protocol
Example 1
Create a file with the name "reqProtocol.js" and copy the following code snippet. After creating the file, use the command "node reqProtocol.js" to run this code as shown in the example below −
// req.protocol Property Demo Example // Importing the express module 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("Request Protocol received is: ", req.protocol); res.send(req.protocol); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Hit the following Endpoint with a GET request − localhost:3000/api
Output
C:\home
ode>> node reqProtocol.js Server listening on PORT 3000 Request Protocol received is: http
Example 2
Let's take a look at one more example.
// req.protocol Property Demo Example // Importing the express module 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 settings app.enable('trust proxy'); // Defining an endpoint app.get('/api', function (req, res) { console.log("Request Protocol received is: ", req.protocol); res.send(req.protocol); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Hit the following Endpoint with a GET request −
localhost:3000/api
And set the following headers −
- X-Forwarded-Proto = https
Output
C:\home
ode>> node reqProtocol.js Server listening on PORT 3000 Request Protocol received is: https
Advertisements