简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM