【问题标题】:node.js proxying with request: DELETE method not workingnode.js 代理请求:DELETE 方法不起作用
【发布时间】:2016-07-18 08:03:30
【问题描述】:

我需要将任何以api 开头的请求转发到另一台服务器。我像这样使用expressrequest

    var API_SERVER_HOST = "http://something.lala/output-api";

    // call the packages we need
    var express = require( 'express' );
    var request = require( 'request' );

    var port = process.env.PORT || 8080;  // set our port
    var app = express();                  // define our app using express

    // all of our routes will be prefixed with /api
    app.use( express.static( 'webapp' ) ); // static content
    app.use( '/api', function( req, res ){   // proxying
        var url = API_SERVER_HOST + req.url;
        console.log(" - " + req.url + " => " + url + " " + req.method);
        req.pipe( request( url ) ).pipe( res );
    } );

    // launch
    app.listen( port );
    console.log( 'Magic happens on port ' + port );

到目前为止,一切都很好:GET, POST, PUT 工作就像一个魅力,但 DELETE 方法最终会得到一个错误的请求。日志是正确的:正确的 url 和删除方法。如果我将日志的 url 复制粘贴到 curl -X DELETE,它就像一个魅力。

请求管道没有处理 DELETE 方法吗?有什么想法吗?

【问题讨论】:

    标签: node.js express proxy request


    【解决方案1】:

    好的,对于那些遇到同样问题的人,我通过使用http-proxy 而不是requests 进行转发来解决我的问题。代码变为:

    var API_SERVER_HOST = "http://something.lala/output-api";
    
    var express = require( 'express' );
    var request = require( 'request' );
    // use http-proxy instead of requests
    var proxy = require('http-proxy').createProxyServer({ host: API_SERVER_HOST });
    
    var port = process.env.PORT || 8088;  
    var app = express();                 
    
    
    // setup redirect
    app.use('/api', function(req, res, next) {
        proxy.web(req, res, {
            target: API_SERVER_HOST
        }, next);
    });
    
    // listen to redirects (for logging purposes only)
    proxy.on('proxyReq', function(proxyReq, req, res, options) {
        console.log("request : url=", req.url, req.body ? "body=" + req.body : "");
        console.log("response: status=", res.statusCode);
    });
    

    它适用于任何类型的请求,并且可以完美地处理正文、查询和 url 参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      相关资源
      最近更新 更多