1

我将 Node.JS 与 Express、Angular.JS 和 ACL 的节点模块连接角色一起使用。我想允许 user.status 为“Platinum”的用户访问“Platinum”而不是“Gold”,反之亦然。

我的 ACL 部分正在工作,如果我在导航栏中输入 /Platinum,我无法访问 /Gold,但是当我尝试访问 /Platinum 时,我只能获得模板而不是 root shell,所以出现的是:

You made it!
You have the {{status}} status!

如果我单击指向 /Platinum 的 Angular 链接,则一切正常。如果我在导航栏中输入任何中性地址,一切正常。

这应该很容易解决,但我还没有弄清楚。

这是设置授权的代码,我很确定这里一切正常。

ConnectRoles = require('connect-roles')



var user = new ConnectRoles({
    failureHandler: function(req, res, action){
        var accept = req.headers.accept || '';
        res.status(403);
        if(accept.indexOf('html')) {
            res.render('access-denied', {action: action});
        } else {
            res.send('Access Denied - You don\'t have permission to: ' + action);
        }
    }
});

var app = express();

app.use(user.middleware());

// Setting up user authorizations,
// i.e. if req.user.status = "Platinum", they are given Platinum status

user.use('Platinum', function(req) {
    if (req.user.status == 'Platinum') {
        return true;
    }
});
user.use('Gold', function(req) {
    if (req.user.status == 'Gold') {
        return true;
    }
});
user.use('Admin', function(req) {
    if (req.user.status == 'Admin') {
        return true;
    }
});

这设置了授权,现在问题出在路由下面。

app.post('/login', passport.authenticate('local', 
    { successRedirect: '/', failureRedirect: '/login' }));

app.get('/Platinum', user.is('Platinum'), function(req, res) {

  //Obviously the code below is wrong.
    res.render('templates/support/Platinum');
});

app.get('/Gold', user.is('Gold'), function(req, res) {
    res.render('templates/support/Gold');
});
4

1 回答 1

1

您在服务器端配置路由的方式(使用 express)不正确。对于像 AngularJS 这样的单页应用程序,您需要在客户端(即在 Angular 中)完成所有页面的路由。但是,服务器仍然为 API 请求(例如获取和发布数据)和静态资源(index.html、部分 HTML 文件、图像、javascript、字体等)定义路由。

因此,以下代码在您的服务器端 JS 中是错误的:

app.get('/Platinum', user.is('Platinum'), function(req, res) {

  //Obviously the code below is wrong.
    res.render('templates/support/Platinum');
});

app.get('/Gold', user.is('Gold'), function(req, res) {
    res.render('templates/support/Gold');
});

只需删除这些行。

相反,您需要定义服务器将处理的路由,例如您/login的第一个帖子,以及如何获取静态文件(我建议/pub在 URL 中将它们全部作为前缀)。然后,如果没有匹配的路由,您需要执行类似于此答案中的技术来返回您的页面。index.html

这样,当用户键入时http://localhost:port/Gold,express 将看到没有为 定义路由/Gold,因此它将返回index.html,这将加载 AngularJS,运行您的 Angular 应用程序,然后查看 URL 并查看是否与您的任何路由匹配AngularJS 应用程序已配置,如果是,则获取该页面的部分并将其插入您的ng-view(如果使用核心路由器)。

于 2015-03-20T03:27:49.560 回答