我进入用户登录页面后,使用passport.js对用户进行身份验证。为了使用户在返回首页时保持登录状态,我将使用类似以下内容:
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
if(req.user){
// connect to database ....
} else{
res.sendFile(__dirname +'/index.html');
}
});
请注意,index.html文件位于“ public”文件夹中。最近,我意识到具有以上代码的node.js并不使用app.get('/'....)路由,而是直接提供index.html。所以我无法检查req.user是否存在。有什么建议吗?
答案 0 :(得分:0)
您可能会理解express.static
在路由器之前处理index.html。
但是您也不能避免express.static(否则,您必须使用nginx或编写自己的静态文件输出)。
因此,您必须重新考虑您的文件夹结构,或者必须开发2个独立的应用程序:api(后端)和前端(将向api请求数据)
针对您的问题,我编写了一个示例应用程序,用于组织资产,html文件和应用程序路由:
1)具有这样的文件夹结构:
2)和示例app.js
:
'use strict';
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
app.set('trust proxy', 1);
// attaching renderer
app.engine('.html', require('ejs').renderFile); // ejs renderer will render .html files as ejs files
app.set('view engine', 'html'); // views has .html extension
app.set('views', __dirname + '/public'); // views live in public folder
// attaching common middlewares
app.use('/assets', express.static('public/assets')); // our static assets will live in public/assets folder
app.use(cookieParser());
app.use(bodyParser());
// implement and attach passport auth somewhere (:
// remove it after passport has been attached:
const authorizeUser = (req, res, next) => {
req.user = {id: 1, username: 'test'};
next();
};
app.get('/', authorizeUser, (req, res) => {
res.render('index', {user: req.user}); // render get index.html from views folder (see above)
});
app.listen(8080, () => {
console.log('App listening');
});
ps。下载示例应用from here(不要忘记在提取的文件夹(;)中调用npm i
p.s。自己实现passport.js