2016-11-10 118 views
0

我有一個nodejs服務器應用程序,它向客戶端應用程序提供一個API。 此前,應用程序會發送一個AJAX請求,其中包含請求對象中的一個action參數req.body.action,並將其傳遞給主路由(我的意思是「/」),以便根據此參數執行操作。 但是,我需要將任何AJAX POST請求的路由從主路由'/'更改/重定向到動作特定路由'/ {action route}'。如何將POST請求重定向到Nodejs中的其他路由

N.B .:我想爲每個未更新客戶端應用程序的用戶提供向後兼容性,以考慮此更改。即不能修改這些用戶的AJAX請求代碼。

我已經嘗試了下面的這段代碼,但它不起作用。

app.use(bodyParser.json()); 

app.post('/', function(req, res){ 
    if((req.body.action) && (req.body.action === 'action-1')){ 
     res.redirect(307, '/action-1'); 
    } 
    if((req.body.action) && (req.body.action === 'action-2')){ 
     res.redirect(307, '/action-2'); 
    } 
}); 


app.post("/action-1", function (req, res) { 
    //would have proceeded the request for action-1 here but it's not routed 
}); 
app.post("/action-2", function (req, res) { 
    //would have proceeded the request for action02 here but it's not routed 
}); 

回答

0

你可以試試這個方法:

app.use(bodyParser.json()); 

app.post('/', function(req, res){ 
    if((req.body.action) && (req.body.action === 'action-1')){ 
     return routes.act1(req, res); 
    } 
    if((req.body.action) && (req.body.action === 'action-2')){ 
     return routes.act2(req, res); 
    } 
}); 

app.post("/action-1", routes.act1); 
app.post("/action-2", routes.act2); 

它不是重定向,但工程。

相關問題