虽然我还没有找到 Express.js + routing-controllers 的惯用代码,但依靠 GitHub 讨论中的 thishint,我想它会是:
import HTTPS from "https";
import Path from "path";
import BodyParser from "body-parser";
import createExpressApplication from "express";
import type { Express as ExpressApplication } from "express";
import { useExpressServer as supportClassSyntax } from "routing-controllers";
const expressApplication: ExpressApplication = createExpressApplication().
// Use various plugins
use(BodyParser.json());
HTTPS.createServer(
{
key: FileSystem.readFileSync(
Path.join(process.cwd(), "ssl" "SSL_Key-FrontServer.LocalDevelopment.pem"), "utf8"
),
cert: FileSystem.readFileSync(
Path.join(process.cwd(), "ssl", "SSL_Certificate-FrontServer.LocalDevelopment.pem"), "utf8"
)
},
expressApplication
);
supportClassSyntax(
expressApplication,
{
controllers: [
// ...
]
}
).
listen(
443,
(): void => {
console.log("Server started")
}
);
请注意,我已确认 SSL 证书和 SSL 密钥的路径是正确的,因为如果我故意指定错误的 SSL 证书和/或 SSL 密钥路径,应用程序将崩溃并显示“错误:ENOENT:没有此类文件或目录” ”.
如果尝试访问“https://localhost:443”,则会在浏览器中出现“该站点可以'提供安全连接”错误(我的界面有日语,所以我使用了相同英文的侧面屏幕截图消息,并且此屏幕截图中的“domainin.com”在我的情况下实际上是“localhost:443”):
但是,
http://localhost:443/
有效。
怎么了?我不需要 http,我需要 https。
“路由控制器”中的函数
useExpressServer
(我将其别名为 supportClassSyntax
)返回具有 listen
方法的 Express 应用程序的实例。这里应该没有错误。
通过 mkcert 实用程序:
mkcert localhost 127.0.0.1
据我所知,端口号并不重要。
我相信你的主要问题是你正在从你的别名
listen
返回的服务器上调用useExpressServer
,它不知道你的证书:
supportClassSyntax(
expressApplication,
{
controllers: [
// ...
]
}
).listen(443, (): void => { // <--- don't call listen here
console.log('server started')
})
相反,您应该从
https
服务器调用监听,同时仅将带有任何已配置中间件的 Express 应用程序传递到 useExpressServer
。
import HTTPS from "https";
import Path from "path";
import BodyParser from "body-parser";
import createExpressApplication from "express";
import type { Express as ExpressApplication } from "express";
import { useExpressServer as supportClassSyntax } from "routing-controllers";
const expressApplication: ExpressApplication = createExpressApplication()
expressApplication.use(BodyParser.json());
HTTPS.createServer(
{
key: FileSystem.readFileSync(
Path.join(process.cwd(), "ssl" "SSL_Key-FrontServer.LocalDevelopment.pem"), "utf8"
),
cert: FileSystem.readFileSync(
Path.join(process.cwd(), "ssl", "SSL_Certificate-FrontServer.LocalDevelopment.pem"), "utf8"
)
},
expressApplication
);
supportClassSyntax(
expressApplication,
{
controllers: [
// ...
]
}
)
// Now call listen from your HTTPS server with the configured certificate
HTTPS.listen(443, () => {
console.log("server started")
});