简体   繁体   English

用get的express.js静态html

[英]express.js static html with get

On the front page of my app, the user can register an account and then login. 在我的应用程序的首页上,用户可以注册一个帐户,然后登录。 It is expressed as a login and register button on the front page which then show the appropriate form when either are clicked. 它在首页上表示为登录和注册按钮,单击任一按钮时将显示相应的表格。

I would like to replace the two buttons with a log out button if the user is already logged in but I need to inform the client of that first. 如果用户已经登录,我想用注销按钮替换这两个按钮,但是我需要先告知客户。

In my index.js, I am serving static html like so 在我的index.js中,我正在像这样提供静态html

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

I thought I could then do the following 我以为我可以做到以下几点

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

but the callback is never called 但是永远不会调用回调

Umm! 嗯! i guess there would be a login/register form so there has to be two routes one with .get() and second one with .post() : 我想会有一个登录/注册表格,所以必须有两条路线,一条是.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
});

and i guess you have set up this: 我想你已经设置了:

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

if not then you have to load this module require('body-parser') first and require it only if you are using express 4 . 如果不是,则必须首先加载此模块require('body-parser') ,并且仅在使用express 4时才需要它。

I have found a solution. 我找到了解决方案。

In my index.js, I have this 在我的index.js中,我有这个

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

And then I can just send a get request for /isloggedin and handle the result 然后我可以发送对/ isloggedin的获取请求并处理结果

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM