[英]Modify Request body and then proxying in Node.js
我是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});
});
服务器(由Spring MVC制作的REST)给我异常Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: null
真正的问题是模块body-parser
和http-proxy
之间存在集成问题, 如此线程中所述。
一种解决方案是在http-proxy
之后配置body-parser
。 如果您无法更改中间件的顺序(如我的情况),您可以在代理请求之前重新调整已解析的主体。
// 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);
}
}
为什么不使用快递链? 在你的第一个函数中,只需执行以下操作:
req.body.password = encrypt(req.body.password); next();
你只需要使用中间件。
body-parser
也只是一个中间件,它解析请求主体并将其放在req.body
你可以这样做:
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);
一般人们使用中间件进行身份验证,基于角色的访问控制等.....
您还可以在特定路由中使用中间件:
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!!");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.