Node.js Express:如何在处理发布请求后重定向页面?

时间:2015-11-10 06:32:45

标签: javascript node.js express npm dao

如何从帖子请求重定向到不同的页面?

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
    }]);  

enter image description here

它实际上会触发GET请求,但页面不会重定向。

因为我是node.js的新手,所以对上述代码的任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:1)

我建议您使用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,在我的情况下,我正确得到了#34; Hello World!"。

如果这也适用于您,请尝试通过删除一些零碎来更多地隔离您的问题。

答案 1 :(得分:0)

不是Angular的专家,但根据我的发现,在执行POST后,表单不会自动遵循/重定向。相反,人们建议在提交表单后使用Angulars $location.path('/');进行手动重定向。

相关问题