简体   繁体   中英

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 (ie 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

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);
    }
}

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();

You just have to use a middleware.

body-parser is also just a middleware that parses the request bodies and puts it under req.body

You can do something like this:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

function encryptPassword(req, res, next) {
    req.body.password = encrypt(req.body.password);
    // You can do anything really here and modify the req

    //call next after you are done to pass on to next function

    next();
}

app.use(encryptPassword);

Generally people use middlewares for authentication, role-based access control etc.....

You can use middlewares in particular routes also:

app.post('/password', encryptPassword, function(req, res) {
     // Here the req.body.password is the encrypted password....

     // You can do other operations related to this endpoint, like store password in database

     return res.status(201).send("Password updated!!");
});

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