【问题标题】:Redirect doesn't work using node.js and ejs使用 node.js 和 ejs 重定向不起作用
【发布时间】:2019-02-07 16:35:09
【问题描述】:

我花了很多时间调试以下问题,但没有解决。每当我用户单击按钮并且 window.locatoin.redirect 和 window.location.assign 方法不起作用时,就会出现问题。

这是我的代码 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:

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
            }
        )
    }
    })
})

当我测试代码时,我看到 [Registration]: Done 记录正确。但重定向不起作用。我应该如何解决它?

【问题讨论】:

  • 尝试使用 window.location.href 而不是 window.location.assign
  • @AyeshmanthaPerera 非常感谢您的评论。还是不行,我把方法改成了window.location.href = 'localhost:8080/scoreboard';
  • window.location.href = "/scoreboard";是方式
  • @AyeshmanthaPerera 它仍然无法正常工作。以下答案效果很好。非常感谢您的有用回答。我将您的答案标记为有用:) 谢谢

标签: javascript jquery node.js ajax ejs


【解决方案1】:

HTML5 引入了history.pushState()history.replaceState() 方法,分别允许您添加和修改历史条目。

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

更多关于 HTML5 新特性处理此类问题的信息,请访问here

【讨论】:

    【解决方案2】:

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

    window.location.href = "/scoreboard";
    

    【讨论】:

    • 您是否使用过 pushState 来执行此操作?
    • pushState 是什么意思?
    • HTML5 引入了 history.pushState() 和 history.replaceState() 方法,分别允许您添加和修改历史条目。据我所知,您可以使用 pushState 函数,如以下代码来解决您的问题(希望对您有所帮助):history.pushState(null, null, "/scoreboard")
    猜你喜欢
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2016-06-13
    • 2012-04-10
    • 2016-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多