【问题标题】:res.redirect does not reload the page to the new endpointres.redirect 不会将页面重新加载到新端点
【发布时间】:2020-05-13 23:13:26
【问题描述】:

我正在为一个测验应用程序编写一个登录页面。在按下登录按钮时,我正在向服务器发送一个发布请求,服务器重定向到列出问题的主页。问题是它只刷新登录页面。

  // FRONT-END code
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;

  const xhr = new XMLHttpRequest();

  // I only put this in to reload the page somehow
  xhr.onreadystatechange = () => {
    window.location.href = '/';
  };

  xhr.open('POST', '/login');
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.send(JSON.stringify({
    username,
    password,
  }));
// SERVER-SIDE code
router.post('/login', jsonParser, (req, res) => {
  if (req.body.username === undefined || req.body.password === undefined) {
    console.log('Doesn\'t have neccesarry elements');
    res.status(400).render('error', { message: 'Doesn\'t have necessary elements' });
  } else {
    ...
    res.redirect('/');
  }
});

我想提一下/也是一个模板渲染的页面,也许这就是问题所在?

【问题讨论】:

    标签: javascript node.js express redirect xmlhttprequest


    【解决方案1】:

    问题出在您的前端,如果客户端使用 xml 请求请求服务器,则不会重定向页面。所以你必须在xml请求之后从客户端window.location.href重定向。

    1.如果服务端出错,就这样发送{status: error}给客户, 2.检查客户端的状态,如果错误改变clien中的路径。

    【讨论】:

    • 所以我无意中写了正确的语法?
    • @BalogSzilárd 是的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 2018-11-30
    • 2020-05-30
    • 2013-01-31
    • 2017-01-28
    • 2020-06-22
    相关资源
    最近更新 更多