【问题标题】:express.js static html with getexpress.js 静态 html 与 get
【发布时间】:2015-07-10 06:57:29
【问题描述】:

在我的应用程序的首页,用户可以注册一个帐户然后登录。它表示为首页上的登录和注册按钮,然后在单击任何一个时显示相应的表单。

如果用户已经登录,我想用注销按钮替换这两个按钮,但我需要先通知客户。

在我的 index.js 中,我像这样提供静态 html

app.use(express.static('public'));

我认为我可以执行以下操作

app.get('/', function(req, res) {
    // inform the client if req.user isn't null
});

但从不调用回调

【问题讨论】:

  • 因为express.static 不是/ 路由。尝试在public/ url 中导航并查看差异。
  • express.static() 旨在提供来自public 文件夹的静态资源,并且还需要var path = require('path')
  • 我现在更好地理解了提供静态资源意味着什么。对于我要完成的工作,您有什么建议?

标签: javascript node.js express passport.js passport-local


【解决方案1】:

我找到了解决办法。

在我的 index.js 中,我有这个

app.get('/isloggedin', function(req, res) {
    res.json({ loggedin: (req.user != null) });
});

然后我可以发送一个获取 /isloggedin 的请求并处理结果

$.get('/isloggedin', {}, function(data) {
    if (!data.loggedin) {
        // remove logged-in only elements
    } else {
        // remove logged-out only elements
    }
});

【讨论】:

    【解决方案2】:

    嗯!我想会有一个登录/注册表单,所以必须有两条路线,一条是.get(),第二条是.post()

    app.get('/', function(req, res) {
        // This is for navigation to the home page
    }).post('/', function(req, res){
        // inform the client here about the req.body.user
    });
    

    我猜你已经设置了这个:

    app.use(bodyParser.urlencoded({extended:true})); // for "formurlencoded"
    app.use(bodyParser.json()); // for "application/json"
    

    如果没有,那么您必须先加载此模块require('body-parser'),并且仅在您使用 express 4 时才需要它。

    【讨论】:

    • 请重新阅读原始问题。我已经进行了注册,并且我相信我的登录也可以使用;但是,如果用户实际上已登录,我需要用注销按钮替换第一页上的登录和注册按钮。
    猜你喜欢
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 2017-05-16
    • 2012-05-13
    相关资源
    最近更新 更多