Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify Request body and then proxying in Node.js

I am a relative newbie of Node.js. It been two days that I am trying to modify the body of a Request in Node.js and then forwarding it. For proxying I am using http-proxy module.

What I have to do is to intercept the password of a user inside a JSON object, encrypting it and set the new encrypted password inside the request body.

The problem is that every time I try to collect the request body I consume it (i.e. using body-parser). How can I accomplish this task? I know that the Request in node is seen has a stream.

For sake o completeness, I am using express to chain multiple operation before proxying.

EDIT

The fact that I have to proxy the request is not useless. It follows the code that I am trying to use.

function encipher(req, res, next){
    var password = req.body.password;
    var encryptionData = Crypto().saltHashPassword(password);
    req.body.password = encryptionData.passwordHash;
    req.body['salt'] = encryptionData.salt;
    next();
}

server.post("/users", bodyParser.json(), encipher, function(req, res) {
    apiProxy.web(req, res, {target: apiUserForwardingUrl});
});

The server (REST made by Spring MVC) give me the exception Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: null

like image 827
riccardo.cardin Avatar asked Oct 04 '16 08:10

riccardo.cardin


2 Answers

The real problem is that there is an integration problem between modules body-parser and http-proxy, as stated in this thread.

One solution is to configure body-parser after http-proxy. If you can't change the order of the middleware (as in my case), you can restream the parsed body before proxying the request.

// restream parsed body before proxying
proxy.on('proxyReq', function(proxyReq, req, res, options) {
    if (req.body) {
        let bodyData = JSON.stringify(req.body);
        // if content-type is application/x-www-form-urlencoded -> we need to change to application/json
        proxyReq.setHeader('Content-Type','application/json');
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
        // stream the content
        proxyReq.write(bodyData);
    }
}
like image 93
riccardo.cardin Avatar answered Nov 17 '22 03:11

riccardo.cardin


Why don't use express chaining for this ? In your first function just do something like this :

req.body.password = encrypt(req.body.password); next();

like image 1
Steeve Pitis Avatar answered Nov 17 '22 01:11

Steeve Pitis