Node.js Express : How to redirect page after processing post request?

纵然是瞬间 提交于 2019-12-13 14:25:30

问题


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  
            }*/
        });
    });  
};

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

It actually triggers the GET request but the page won't redirect.

Since I am new in node.js, any kind of suggestion for the above code would be appreciated.


回答1:


I suggest you to leverage next, so something like

app.post('/', handlePostOnRoot);

app.post('/createStation', [
  function(req, res, next){
    next()       
  },
  handlePostOnRoot
]);

On the subject: http://expressjs.com/guide/routing.html#route-handlers

EDIT based on comment:

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

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.




回答2:


Not an expert in Angular, but from what I can find, the form won't automatically follow the / redirect after doing the POST. Instead, people recommend using Angulars $location.path('/'); to do a manual redirect after the form was submitted.



来源:https://stackoverflow.com/questions/33624188/node-js-express-how-to-redirect-page-after-processing-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!