Express.js req.protocol属性的用法介绍

2021年3月26日16:52:19 发表评论 672 次浏览

要求协议属性包含请求协议字符串, 可以是HTTP或(对于TLS请求)https。当信任代理设置的评估结果不为false时, 此属性将使用X-Forwarded-Proto标头字段值(如果存在)。

语法如下:

req.protocol

参数:没有参数。

返回值:串。

快递模块的安装:

  1. 你可以访问以下链接安装快递模块。你可以使用此命令安装此软件包。
    npm install express
  2. 安装Express模块​​后, 可以使用命令在命令提示符下检查Express版本。
    npm version express
  3. 之后, 你可以仅创建一个文件夹并添加一个文件, 例如index.js。要运行此文件, 你需要运行以下命令。
    node index.js

范例1:

文件名:index.js

var express = require( 'express' );
var app = express(); 
var PORT = 3000;
  
app.get( '/' , function (req, res) {
   console.log(req.protocol);
   res.send();
});
  
app.listen(PORT, function (err){
     if (err) console.log(err);
     console.log( "Server listening on PORT" , PORT);
});

运行程序的步骤:

项目结构将如下所示:

Express.js req.protocol属性1

确保使用以下命令安装了Express模块​​:npm install express

使用以下命令运行index.js文件:node index.js输出:服务器在PORT 3000上侦听

现在打开浏览器并转到http:// localhost:3000 /, 现在你可以在控制台上看到以下输出:服务器在PORT 3000 http上侦听

范例2:考虑上面的代码, 但假定此项目已部署在Https服务器上, 如下所示:

https://www.example.com

现在, 如果我们尝试打印要求协议值, 将是以下输出:

https

参考: https://expressjs.com/cn/4x/api.html#req.protocol


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: