【发布时间】:2021-11-24 11:53:22
【问题描述】:
所以发生的情况是 app.use('*') 甚至 app.get 都没有捕捉到主路由,并且在你转到任何其他路由之前不会重定向到 https。
关于是什么原因的任何线索?
const express = require('express');
const path = require('path');
const app = express();
const http = require('http');
const https = require('https');
const fs = require('fs');
//Hiding cert information
const credentials = {
key: privateKey,
cert: certificate,
ca: ca
};
app.enable('trust proxy')
const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);
httpServer.listen(80, () => {
console.log('HTTP Server running on port 80');
});
httpsServer.listen(443, () => {
console.log('HTTPS Server running on port 443');
});
app.use((req, res, next) => {
req.secure ? next() : res.redirect('https://' + req.headers.host + req.url)
})
//Moved it to be underneath the http middleware
app.use(express.static(path.join(__dirname, './website/build'), { dotfiles: 'allow' }));
app.use((req, res) => {
res.sendFile(path.join(__dirname, './website/build/index.html'));
});
访问该网站没有任何作用,但第二次访问任何非家庭路线都可以。
编辑:
原来问题在于 app.use(express.static()) 优先于 https 重定向中间件。像这样改变它解决了问题
【问题讨论】:
-
你能显示其他路径的路由器吗?也是你的“应用”快递吗?为什么要使用 http 创建服务器?
-
我认为我们必须按照声明的确切顺序查看所有代码。如果
app已在两台服务器上注册,并且您显示的第一个app.use()语句是第一个,那么它应该在每个传入请求时首先破解。但是,如果您有其他类似express.static()路线 FIRST 的东西,那么所有的赌注都没有了。我们需要查看所有代码。 -
已编辑以添加完整代码,这可能是快速静态我会尝试弄乱它,但不知道这可能是什么原因。
标签: node.js express http https routes