[英]How to use express response to stay in the same page without redirect?
Consider a simple form which takes email as input.考虑一个将电子邮件作为输入的简单表单。 Submit button calls a bootstrap modal in case authentication failed.
如果身份验证失败,提交按钮将调用引导模式。 If at success, it redirects to the next view.
如果成功,则重定向到下一个视图。
When bootstrap modal appears, the browser is constantly loading the page, waiting a response.当 bootstrap modal 出现时,浏览器一直在加载页面,等待响应。
I am using this code on server side:我在服务器端使用此代码:
app.post('/', (req, res) => {
Users.findOne({
email: req.body.email
})
.then(user => {
if (user) {
obj = req.body.email
res.redirect('/survey')
}
})
})
I tried to add an else
statement in case user is not found:如果找不到用户,我尝试添加
else
语句:
...
else {
console.log('User not found')
return
}
I do not want to redirect to the same page because modal will not work.我不想重定向到同一页面,因为模态不起作用。
Is there a res
method in order to achieve this?是否有
res
方法来实现这一目标?
The proper solution will be to use ajax for submitting form data & handling response正确的解决方案是使用 ajax 提交表单数据和处理响应
based on the response success / failure, you can redirect user or show modal for error from client side根据响应成功/失败,您可以重定向用户或显示来自客户端的错误模式
If you still want to do it without ajax submission of form, you can redirect user to same url with adding querystring如果您仍然想在没有 ajax 提交表单的情况下执行此操作,您可以通过添加查询字符串将用户重定向到相同的 url
res.redirect('/same-path?error=user_not_found')
And check query params on load of page in client javascript并在客户端 javascript 中检查页面加载时的查询参数
$(document).ready ( function(){
var url = window.location.search;
var queryStr = url.split("?")[1];
if(queryStr) {
let hash = queryStr.split('&);
for (var i = 0; i < hash.length; i++) {
params=hash[i].split("=");
if(params[0] == 'error' && params[1] == 'user_not_found') {
// SHOW YOUR MODAL HERE
}
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.