简体   繁体   中英

nodejs proxy with express and mikeal/request library

I'm trying to do a simple proxy with express js and mikeal/request library:
Client side app calls expressjs on certain path (/api) and all requests get forwarded to remote machine.
It does not work, i must be missing something obvious.

expressjs code:

app.use('/api', function(req, res) {
    var url = config.api + req.url;
    var auth = authlib.createTokenHeader(req.user) || {};
    var forwarded = { 'X-Forwarded-For': req.connection.remoteAddress };
    console.log('Forwarding to api ' + url);
    req.pipe(request({
        uri:url,
        headers: _.merge(authlib.stripSensitiveHeaders(req.headers), auth, forwarded),
    })).pipe(res);
});

When issuing PUT request to http://localhost:9000/api/account , grunt log shows:

Forwarding to api http://xxx.xxx.xxx/account
PUT /api/account 200 120005ms
Forwarding to api http://xxx.xxx.xxx/account
PUT /api/account 200 120006ms

And on the remote API, apache logs show that requests were made:

xx.xx.xx.xx - - [23/Feb/2014:17:44:23 +0000] "PUT /account HTTP/1.1" 400 189 "http://localhost:9000/login" "Mozilla/5.0"
xx.xx.xx.xx - - [23/Feb/2014:17:46:23 +0000] "PUT /account HTTP/1.1" 400 189 "http://localhost:9000/login" "Mozilla/5.0"

And eventually Chrome gives out that empty response was received:

PUT http://localhost:9000/api/account net::ERR_EMPTY_RESPONSE 

Question is why am i getting two requests, and where does the 120s timeout come from?

I've tried to make it simplier, but results are the same:

app.use('/api', function(req, res) {
  req.pipe(request(config.api + req.url)).pipe(res);
});

And it works if i post using something like Postman from Chrome on the same machine to the http://xxx.xxx.xxx/account endpoint

Finaly found the problem, which is not related to this code.

Since i'm using yeoman full stack template, expressjs had various other settings, and the one that messed things was json:

app.use(express.json());

Removing this line solved the problem. Now i need to figure out why :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM