如何从 post 请求重定向到不同的页面?
module.exports = function(app) {
app.post('/createStation', function(request, response){
response.redirect('/'); //This doesn't work, why and how to make this work
/*var stationDao = require('./server/stationDao.js');
stationDao.stationDao.createStation(request.body, function(status){
if(status.status == 'successful'){
response.redirect('/'); //This is what actually I wanted to do
}*/
});
});
};
也尝试使用 next(),
app.post('/createStation', [function(request, response, next){
var stationDao = require('./server/stationDao.js');
stationDao.stationDao.createStation(request.body, function(status){
if(status.status == 'successful'){
next();
}
});
}, function abc(request, response){
console.log('I can see this');
response.redirect('/'); //This doesn't work still
}]);
它实际上触发了 GET 请求,但页面不会重定向。
由于我是 node.js 的新手,对于上述代码的任何建议都将不胜感激。
最佳答案
我建议你利用next
,比如
app.post('/', handlePostOnRoot);
app.post('/createStation', [
function(req, res, next){
next()
},
handlePostOnRoot
]);
关于主题:http://expressjs.com/guide/routing.html#route-handlers
编辑基于评论:
我刚刚编写了一个非常基本的服务器来测试我写的内容:
var express = require('express');
var app = express();
app.post('/a', [function(req, res, next) {
next();
}, function(req, res) {
res.send('Hello World!');
}]);
var server = app.listen(3000, function () { console.log('listening'); });
这对我有用,我鼓励你运行它然后 curl -X POST http://localhost:3000/a
,在我的例子中我正确地得到了“Hello World!”。
如果这对您也有效,请尝试通过删除一些点点滴滴来进一步隔离您的问题。
关于javascript - Node.js express : How to redirect page after processing post request?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33624188/