簡體   English   中英

Node.js Express:如何在處理發布請求后重定向頁面?

[英]Node.js Express : How to redirect page after processing 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(),

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的新手,因此對上述代碼的任何建議都表示贊賞。

我建議你利用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!”。

如果這也適用於您,請嘗試通過刪除一些零碎來更多地隔離您的問題。

不是Angular的專家,但是根據我的發現,表單在執行POST后不會自動跟隨/重定向。 相反,人們建議使用Angulars $location.path('/'); 在提交表單后進行手動重定向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM