代码之家  ›  专栏  ›  技术社区  ›  user3425506

curl:从post路由重定向到get路由

  •  0
  • user3425506  · 技术社区  · 6 年前

    我有一个express应用程序,我希望能够将post请求重定向到get请求。

    以下是应用程序:

    const express = require('express');
    
    const app = express();
    
    app.get('/get-route', function(req, res, next){
        res.redirect('/');
    });
    
    app.post('/post-route', function(req, res, next){
        res.redirect('/');
    });
    
    app.get('/', function(req, res, next){
        res.send('Home Page!\n');
    }); 
    
    app.listen(3001);
    

    steve@Dell ~ $ curl http://localhost:3001/
    Home Page!
    steve@Dell ~ $ curl -L http://localhost:3001/get-route
    Home Page!
    

    在下面的curl请求中,它说它正在重定向到/但我不理解为什么它不显示 Home Page! 消息

    steve@Dell ~ $ curl -X POST http://localhost:3001/post-route
    Found. Redirecting to /
    

    我认为-L选项可能有效,但这会产生一个错误:

    steve@Dell ~ $ curl -L -X POST http://localhost:3001/post-route
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Error</title>
    </head>
    <body>
    <pre>Cannot POST /</pre>
    </body>
    </html>
    

    自从第一次问这个问题以来,我注意到我可以通过使用HTTPie得到我想要的:

    steve@Dell ~ $ http --form --follow POST localhost:3001/post-route
    HTTP/1.1 200 OK
    Connection: keep-alive
    Content-Length: 11
    Content-Type: text/html; charset=utf-8
    Date: Sun, 27 Jan 2019 18:03:14 GMT
    ETag: W/"b-OVE2GcFhwNv2PpVDFXfoBIbNry4"
    X-Powered-By: Express
    
    Home Page!
    

    如果可能的话,我仍然希望能够使用curl。

    1 回复  |  直到 6 年前
        1
  •  1
  •   TXRedking    6 年前

    因此,在上面的原始代码中,您没有指定从post重定向到get路由的状态代码。Express将发送默认状态代码302,这意味着浏览器将返回新位置“/”和get方法。一切都应该很好。。。

    除了使用curl的-X选项时,您无意中告诉curl使用指定的原始方法向该路由发出所有请求(包括重定向)。

    正如下面的链接中所回答的,在这种情况下,您需要使用 旋度s-d选项 因为这是使用curl发送POST请求的预期方法之一。

    curl uses POST for all requests after redirect

    TLDR: curl -L -d POST http://localhost:3001/post-route 应该有用。

    推荐文章