修改请求主体,然后在Node.js中进行代理

ric*_*din 6 javascript proxy spring-mvc node.js express

我是Node.js的相对新手.我试图修改Node.js中的Request的主体然后转发它已经两天了.对于代理,我正在使用http-proxy模块.

我要做的是拦截JSON对象内的用户密码,加密它并在请求体内设置新的加密密码.

问题是每次我尝试收集请求主体时我都会使用它(即使用body-parser).我怎样才能完成这项任务?我知道看到节点中的Request有一个流.

为了完整起见,我express在代理之前使用链接多个操作.

编辑

我必须代理请求的事实并非无用.它遵循我尝试使用的代码.

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});
});
Run Code Online (Sandbox Code Playgroud)

服务器(Spring MVC制作的REST)给了我一个例外 Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: null

ric*_*din 7

真正的问题是,有模块之间的集成问题body-parserhttp-proxy,在规定这个线程.

一种解决方案是配置body-parser之后http-proxy.如果您无法更改中间件的顺序(如我的情况),您可以在代理请求之前重新调整已解析的主体.

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 以防万一它对其他人有帮助:对我来说,我向有效负载添加了更多信息,因此更新内容长度非常重要。我还必须在 `proxyReq.write()` 之后包含 `proxyReq.end()` ,否则请求似乎关闭了,但没有任何说明原因。 (2认同)