gpt4 book ai didi

node.js - 在 LoopbackJS : How to get server protocol (http or https) in a boot script or server side code? 中

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:49 25 4
gpt4 key购买 nike

在服务器端 js 文件中,例如 send-email.js,我正在尝试创建一个超链接来发送电子邮件

var config = require('../../server/config.json');    

function sendEmail() {
var url = config.protocol + '://' + config.host + ':' + config.port + '/login';
//code to send e-mail follows...
}

我在 config.json 文件中配置了协议(protocol)、主机和端口,并使用它们我能够成功创建超链接。

我也在使用boot scripts LoopbackJS 的,其中 app 参数的传递如下代码所示:

module.exports = function (app, cb) {
var url = 'http://' + app.get('host') + ':' + app.get('port') + '/login';
}

我可以获取主机和端口,但不能获取协议(protocol)。

现在有两种方式获取主机和端口:

  1. 使用config.json文件
  2. 使用 app.get 方法

没有 app.get('protocol') 来获取协议(protocol),因此我在 config.json 文件中配置了它,但我想自动获取协议(protocol)以防止在部署到服务器时更改文件。

是否有类似根据此 Nodejs 应用程序的托管位置自动获取协议(protocol)(或主机和地址)之类的内容,而不是对其进行配置。

我愿意接受来自 NodeJS、ExpressJS 或 LoopbackJS 角度的答案。

最佳答案

如果您的主要目标是避免在部署时更改配置文件,那么还有另一种选择。

不要在代码中获取协议(protocol),而是在将运行应用程序的每个主机上设置一个环境变量。然后在 config.local.js 中覆盖 config.json 中的“协议(protocol)”设置。

配置.json:

{
"restApiRoot": "/api",
"host": "0.0.0.0",
"port": 3000,
"protocol": "http"
...
}

config.local.js:

module.exports = {
"host": process.env.APPNAME_API_HOST,
"port": process.env.APPNAME_API_PORT,
"protocol": process.env.APPNAME_API_PROTOCOL
...
}

运行应用程序的用户的服务器引导 config.sh 或 .bashrc(如果是 bash):

export APPNAME_API_HOST=0.0.0.0
export APPNAME_API_PORT=3333
export APPNAME_API_PROTOCOL=https

(如果您使用 Strong-pm 运行,则可以使用 slc ctl servicename env-set ENV=value 命令设置这些值。)

这允许您在设置变量的任何环境中使用相同的 config.local.js 文件,并且环境配置是特定于主机的。无需更改文件,服务器环境配置也可以自动化并 checkin 。

关于node.js - 在 LoopbackJS : How to get server protocol (http or https) in a boot script or server side code? 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33951770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com