我有一個 NodeJS 后端正在運行,它使用 express 框架。在前端,我使用 Angular。過去我構建了兩個 Docker 容器(一個前端,一個后端)。現在我只想構建一個容器,NodeJS 像往常一樣在其中運行。但它也應該提供我的前端。它正在作業,所以這是我的代碼:
import express = require("express");
import session = require('express-session');
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const port = process.env.PORT || 80;
...
const isOnline: RequestHandler = (req: express.Request, res: express.Response, next: express.NextFunction) => {
if (!req.session.user) {
return res.redirect('/auth/login?rd=' req.originalUrl);
}
next();
};
...
app.use('/api', isOnline, apiRoutes);
app.use('/auth', authRoutes);
app.get('*.*', express.static(path.join('./', 'dist'), {maxAge: '1y'}));
app.get('*', isOnline, (req: express.Request, res: express.Response) => {
res.status(200).sendFile(`/`, {root: path.join('./', 'dist')});
});
app.listen(port, () => console.log('API running on port ' port));
代碼說明
所以實際上有三種型別的路線。API、授權和前端路徑。API 和前端應該只能由授權的用戶訪問。授權適用于所有人。
問題/問題
The issue is, that I provide all files from the dist folder (in which my build angular app is located), which has a dot (so all file names). And when I open the app (example.com), I will directly redirect to the auth route. This means the middleware is working. But if add the index file to the path (example.com/index.html), I have access to the app directly, because it is provided by the . route.
Solution Ideas Is there maybe any way to exclude the index.html from the wildcard statement (or do I stop providing angular by this)? Can I catch the route exmpla.com/index.html and redirect to the base path? Or is there any other way to protect my whole angular app by my middleware?
uj5u.com熱心網友回復:
您可能會完全關閉公共(dist)檔案夾:
app.get('*.*', isOnline, express.static(path.join('./', 'dist'), {maxAge: '1y'}));
僅公開開放 api 和登錄路徑
并在 中的登錄路由上authRoutes,使用一些最小的行內 css 和表單或 javascript 呈現登錄頁面以處理登錄:
authRoutes.get('login', /*res.sendFile with styles and login form*/)
authRoutes.post('login', /*handle login*/)
//...
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451982.html
下一篇:在while回圈內多次呼叫函式
