【发布时间】: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