【问题标题】:How to Redirect POST Request to another Route in Nodejs如何将 POST 请求重定向到 Nodejs 中的另一个路由
【发布时间】:2016-11-10 07:16:34
【问题描述】:

我有一个 nodejs 服务器应用程序,它为客户端应用程序提供 API。 以前,应用程序将发送一个 AJAX 请求,其中包含请求对象 req.body.action 中的操作参数到主路由(我的意思是“/”)以根据此参数进行操作。 但是,我需要将任何 AJAX POST 请求的路由从主路由“/”更改/重定向到特定于操作的路由“/{action route}”。

注意:我希望允许尚未更新客户端应用程序的每个用户向后兼容以考虑此更改。即,不能为这些用户修改 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
});

【问题讨论】:

    标签: ajax node.js redirect post routes


    【解决方案1】:

    你可以试试这个方法:

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

    它不是重定向,但有效。

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 2021-05-11
      • 2017-05-07
      • 2011-08-18
      • 2017-03-15
      • 2021-01-06
      相关资源
      最近更新 更多