Express.js 中 req.protocol 属性
req.protocol 属性返回请求协议字符串,该字符串要么是 http,要么是(对于 TLS 请求)https。如果存在,将使用 X-Forwarded-Proto 标头字段的值,前提是传递的信任代理设置不为 False。此标头值可以由客户端或代理设置。
语法
req.protocol
示例 1
创建一个名为 "reqProtocol.js" 的文件,并复制以下代码段。创建文件后,使用命令 "node reqProtocol.js" 运行此代码,如下例所示 −
// 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);
});使用 GET 请求点击以下终结点 − localhost:3000/api
输出
C:\home
ode>> node reqProtocol.js Server listening on PORT 3000 Request Protocol received is: http
示例 2
我们再来看看另一个示例。
// 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);
});使用 GET 请求点击以下终结点 −
localhost:3000/api
并设置以下标头 −
- X-Forwarded-Proto = https
输出
C:\home
ode>> node reqProtocol.js Server listening on PORT 3000 Request Protocol received is: https
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP