【问题标题】:Node.js Express : How to redirect page after processing post request?Node.js Express:处理发布请求后如何重定向页面?
【发布时间】:2016-02-10 23:42:47
【问题描述】:

如何从发布请求重定向到不同的页面?

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 的新手,任何对上述代码的建议都将不胜感激。

【问题讨论】:

  • 你检查status.status == 'successful'是否有效?
  • 您是否尝试过使用普通路由语法而不是使用self.routeTable 编写例程?
  • 没有。为什么你会认为 self.routeTable 会有问题?谢谢
  • 您需要将 statusCode 设置为 302 并在响应 en.wikipedia.org/wiki/HTTP_302 的位置标头上传入您要重定向到的 url
  • 好吧,我提出self.routeTable 的原因是我找不到任何关于它使用的官方文档。可能值得一试app.post('/createStation',function(req,res){})

标签: javascript node.js express npm dao


【解决方案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,在我的例子中,我正确地得到了“Hello World!”。

如果这也适用于您,请尝试通过删除一些零碎的内容来进一步隔离您的问题。

【讨论】:

  • 谢谢,请找到更新后的问题,我试过 next() 但没有用
  • 我没想到 :D 好吧...那么可能是快递版本,你用的是哪一个?我用的是最新的。
  • express => 3.4.4, nodejs => 4.2.2
  • 我有 express 4.13.3 和 node 4.2.1
  • 那我很抱歉,但不能帮你:D,我又试了一次:创建/tmp/server.js 并从/tmp 运行npm install express,它工作正常,你能写curl你用来测试的命令吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 2019-05-31
    • 1970-01-01
    • 2018-12-18
    • 2018-09-11
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多