最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

res.redirect不会将页面重新加载到新端点

IT培训 admin 9浏览 0评论

res.redirect不会将页面重新加载到新端点

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

  // 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('/');
  }
});

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

回答如下:

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

1。如果这样,在向{status: error}发送服务给客户时出错,2.检查客户端中的状态是否错误,请更改clinen中的路径。

res.redirect不会将页面重新加载到新端点

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

  // 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('/');
  }
});

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

回答如下:

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

1。如果这样,在向{status: error}发送服务给客户时出错,2.检查客户端中的状态是否错误,请更改clinen中的路径。

发布评论

评论列表 (0)

  1. 暂无评论