Cod*_*ein 3 node.js express angular
我正在构建一个具有两个独立部分的应用程序,在前端我将其构建为两个独立的 Angular 应用程序。我这样做是为了更好地划分对代码库的控制访问权限,而不是不必要地让一些团队成员访问他们不需要的代码。
所以有两个独立的应用程序,由同一个 NodeJS 服务器提供服务。提供的应用程序取决于用户是否登录。如果他们是访客用户,他们将获得一个版本的应用程序,如果他们是注册用户,他们将获得具有更多功能的特权版本的应用程序。
如何在 Express 中有条件/动态地提供静态文件,以便说“如果User1是客人,则服务Application A,否则服务Application B”?
If it's just one file you're talking about serving (e.g. app-1.js or app-2.js) then you don't need express.static. You can just handle the request in a normal route handler with res.sendFile like so:
app.get('/get-app', function(req, res) {
if (userIsLoggedIn()) {
res.sendFile('/path-to-logged-in-app.js')
} else {
res.sendFile('/path-to-logged-out-app.js')
}
})
Run Code Online (Sandbox Code Playgroud)
More about res.sendFile here.
If you want to serve multiple files via express.static, you'll need two instances of express.static middleware, and another piece of middleware on top of that to modify the request url depending up on the user's logged in status. Maybe something along the lines of the following:
// Middleware function to modify the request url based on user's status
function checkUser(req, res, next) {
if (userIsLoggedIn()) {
req.url = `/app-1/${req.url}`
} else {
req.url = `/app-2/${req.url}`
}
next()
}
// Set up the middleware stack
app.use(checkUser)
app.use('/app-1', express.static(path.join(__dirname, 'app-1')))
app.use('/app-2', express.static(path.join(__dirname, 'app-2')))
Run Code Online (Sandbox Code Playgroud)
More about writing your own middleware here. You also might want to add some logic in checkUser to only prepend to urls requesting static files (e.g. request urls to /assets/foo.js get the prepend treatment but requests to /api/some-api-function do not).
All that said, I'm not that familiar with Angular but I'd suggest investigating other ways to serve logged in / logged out content. I'm assuming there is some concept of components or "views" in Angular, and it's probably a lot cleaner to just render a "LoggedIn" or "LoggedOut" component/view vs. sending a whole different "app".
| 归档时间: |
|
| 查看次数: |
2508 次 |
| 最近记录: |