node.js使用请求代理:DELETE方法不起作用

时间:2016-07-18 08:03:30

标签: node.js express proxy request

我需要将以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和delete方法。如果我将日志的URL粘贴到curl -X DELETE,它就像一个魅力。

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

1 个答案:

答案 0 :(得分:0)

好的,对于那些遇到同样问题的人,我使用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);
});

它适用于任何类型的请求,并处理完美的body,query和url参数。