我已经在这个问题上挣扎了两天,我尽可能地搜索和堆栈溢出,但我不能解决它。
我正在构建一个简单的节点应用程序(+Express + Mongoose),其中包含一个重定向到主页的登录页面。下面是我的服务器JS代码:
app
.get('/', (req, res) => {
console.log("Here we are : root");
return res.sendfile(__dirname + '/index.html');
})
.get('/login', (req, res) => {
console.log("Here we are : '/login'");
return res.sendfile(__dirname + '/login.html');
})
.post('/credentials', (req, res) => {
console.log("Here we are : '/credentials'");
// Some Mongoose / DB validations
return res.redirect('/');
});
登录页面向/credentials
发出POST请求,在那里验证发布的数据。这是可行的。我可以在Node控制台中看到"Here we are:'/credentials'“。
然后问题来了: res.redirect不能正常工作。我知道它确实到达了'/‘路径,因为:
我可以看到Node console
(编辑)重定向在Mongoose的回调函数中,它不是同步的( NodeJS应该是同步的)。为了清楚起见,我刚刚删除了Mongoose验证的东西。
我试过添加res.end()
,但不起作用
我试过了
req.method = 'get';
res.redirect('/');
和
res.writeHead(302, {location: '/'});
res.end();
不起作用
我做错了什么?我如何离开'/login‘页面,将浏览器重定向到'/’,并显示它收到的HTML代码?
提前感谢您的帮助:)
发布于 2017-10-14 04:35:52
问题可能不在后端,而在前端。如果您使用AJAX发送POST请求,它是专门设计为不更改您的url的。
在AJAX的请求完成后使用window.location.href
(在.done()
中)用所需的路径更新URL,或者在收到请求返回的JQuery时使用JQuery:$('body').replaceWith(data)
。
发布于 2020-03-17 11:34:46
如果您使用异步请求到后端,然后在后端重定向,它将在后端重定向(即,它将创建一个新的get请求到该URL),但不会更改前端的URL。
要使其正常工作,您需要:
使用window.location.href = "/url"
<a></a>
)
发布于 2014-11-29 21:15:14
几乎可以肯定的是,您正在进行一个异步调用来检查Mongoose,但是您还没有对代码进行结构化,以便仅在异步调用返回结果之后才会发生重定向。
在javascript中,POST
看起来像这样:
function validateCredentials(user, callback){
// takes whatever you need to validate the visitor as `user`
// uses the `callback` when the results return from Mongoose
}
app.post('/credentials', function(req, res){
console.log("Here was are: '/credentials'";
validateCredentials(userdata, function(err, data){
if (err) {
// handle error and redirect to credentials,
// display an error page, or whatever you want to do here...
}
// if no error, redirect
res.redirect('/');
};
};
你也可以看到像Async call in node.js vs. mongoose这样的问题来解决并行/相关的问题...
https://stackoverflow.com/questions/27202075
复制相似问题