Node.js Express:处理帖子请求后如何重定向页面? [英] Node.js Express : How to redirect page after processing post request?
问题描述
如何从发帖请求重定向到其他页面?
How to redirect to different page from post request ?
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(),
Tried using next() as well,
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请求,但页面不会重定向。
It actually triggers the GET request but the page won't redirect.
由于我是node.js的新用户,因此建议上面的代码将不胜感激。
Since I am new in node.js, any kind of suggestion for the above code would be appreciated.
推荐答案
我建议您利用 next
,例如
app.post('/', handlePostOnRoot);
app.post('/createStation', [
function(req, res, next){
next()
},
handlePostOnRoot
]);
关于主题: http://expressjs.com/guide/routing.html#route-handlers
根据评论进行编辑:
我刚刚编写了一个非常基本的服务器来测试我写的内容:
I've just wrote a really basic server to test what I wrote:
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!。
This works for me, I would encourage you to run that and then curl -X POST http://localhost:3000/a
, in my case I correctly got "Hello World!".
如果这也为您工作,尝试通过删除一些零碎的东西来进一步隔离问题。
If this also works for you try to isolate your problem a bit more by removing some bits and pieces.
这篇关于Node.js Express:处理帖子请求后如何重定向页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!