【发布时间】:2019-08-19 20:07:53
【问题描述】:
我正在尝试使用 ExpressJS 设置服务器,该服务器使用 HTTPS 并为 React 应用程序提供服务器。我希望将任何 HTTP 请求重定向到使用 HTTPS。
附加限制:我正在使用 React 路由器,因此服务器需要能够处理它。例如如果我请求 localhost:3000/profile,我希望 React Router 来处理它,我只需要 Express 来为 index.html 提供服务器,因为我已经去了 localhost:3000。
问题:我想我已经能够设置 HTTPS(Chrome 会抱怨,但我现在不介意),但我无法进行重定向。
作为比较,这是我如何设置仅用于开发的 HTTP 服务器的代码(在我尝试设置 HTTPS 之前):
const express = require('express');
const http = require('http');
const path = require('path');
const app = express();
const DIST_DIR = path.resolve('./dist');
app.use(express.static(DIST_DIR));
app.get('*', (req, res) => {
res.sendFile(path.resolve(DIST_DIR, './index.html'));
});
const devServer = http.createServer(app);
devServer.listen(3000);
接下来,我从this 指南开始。我创建了一个自签名 SSL 证书,然后设置了我的应用程序。然后我看了一些如何重定向的例子,比如this question。
但是,它似乎不起作用。
这是我目前的代码:
app.use(express.static(DIST_DIR));
app.use((req, res, next) => {
if (req.secure) {
next();
} else {
res.redirect(`https://${req.headers.host}${req.url}`);
}
});
app.get('*', (req, res) => {
res.sendFile(path.resolve(DIST_DIR, './index.html'));
});
const httpServer = http.createServer(app);
httpServer.listen(3080);
const privateKey = // uses FS to get my key
const certificate = // uses FS to get my cert
const credentials = { key: privateKey, cert: certificate };
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(3443);
我可以访问https://localhost:3443 并按预期导航应用程序,Express 可以正确处理/profile 等页面上的刷新。伟大的。 Chrome 抱怨“CA 根证书不受信任。将此证书安装在受信任的根证书颁发机构存储中”,但我还没有努力解决这个问题,因为在真实的生产环境中,我会获得证书和密钥来自受信任的来源。
但是,当我转到 http://localhost:3080 时,我只是在 http://localhost:3080 结束。 Chrome devtools 显示我没有使用 HTTPS。此外,我无法直接访问/profile,因为 Chrome 会提示我“此站点无法提供安全连接”的错误。
我尝试了我链接的那个 stackoverflow 问题中列出的其他方法,但它们要么具有相同的行为,要么直接不起作用。我在这里有点脱离我的元素,我正在努力学习,但我不明白为什么这不起作用。任何帮助,将不胜感激。谢谢。
【问题讨论】:
标签: node.js reactjs express react-router