简体   繁体   English

使用 node.js 和 ejs 重定向不起作用

[英]Redirect doesn't work using node.js and ejs

I have spent a lot of time debbuging the following problem but it isn't fixed.我花了很多时间调试以下问题,但没有解决。 The problem occur whenever I the user click on the button and window.locatoin.redirect and window.location.assign methods don't work.每当我用户单击按钮并且 window.locatoin.redirect 和 window.location.assign 方法不起作用时,就会出现问题。

Here is my Code index.ejs:这是我的代码 index.ejs:

function registration() {
        $.post('/user/register', {
            teamName: $('#teamName').val(),
            faculty: $('#faculty').val(),
            email: $('#emailSignUp').val(),
            password: $('#passwordSignUp').val()
        }).done(
            window.location.assign('/scoreboard')
        )
    }

router.js:路由器.js:

router.post('/user/register', (req, res) => {
    var newUser = {
        teamName: req.body.teamName,
        faculty: req.body.faculty,
        email: req.body.email,
        password: req.body.password
    }
    userModel.create(newUser, (err, user) => {
        if (err) {
            console.log('[Registratoin]: ' + err);
        } else {
            console.log('[Registration]: Done');
            req.session.userID = user._id;
            res.redirect('/scoreboard')
        }
    });
})

router.get('/scoreboard', (req, res) => {
    userModel.find({}).sort('-score').exec((err, teams) => {
        if (err) {
            console.log('[scoreboard]: ' + err)
        }
        else{
            res.render('main/scoreboard', {
                teamInformation: teams
            }
        )
    }
    })
})

When I test the code, I see the [Registration]: Done logged correctly.当我测试代码时,我看到[Registration]: Done正确记录。 but redirect doesn't work.但重定向不起作用。 How should I fix it?我该如何解决?

请使用 location.href 而不是 location.assign 如下:

window.location.href = "/scoreboard";

HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively. HTML5 引入了history.pushState()history.replaceState()方法,它们分别允许您添加和修改历史条目。

history.pushState(null, null, "/scoreboard")

More information about the new features of HTML5 to handle these kind of problem are available here .有关处理此类问题的 HTML5 新功能的更多信息,请访问此处

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

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