2016-10-04 4 views
3

저는 Node.js의 상대적으로 초보자입니다. Node.js에서 요청 본문을 수정 한 다음 전달하려고하는 이틀이 지났습니다. 프록시의 경우 http-proxy 모듈을 사용하고 있습니다.요청 본문을 수정 한 다음 Node.js에서 프록시합니다.

내가해야 할 일은 JSON 객체 내부의 사용자 비밀번호를 가로 채서 암호화하고 요청 본문 내에 새로운 암호화 된 비밀번호를 설정하는 것입니다.

문제는 요청 본문을 수집하려고 할 때마다 (즉, body-parser을 사용하여) 소비한다는 것입니다. 이 작업을 어떻게 수행 할 수 있습니까? 나는 노드의 Request가 스트림을 가지고있는 것을 안다.

나는 완전성을 위해 express을 사용하여 프록시 처리 전에 여러 작업을 연결합니다.

편집

의 I 프록시해야한다는 사실 요청이 쓸모가 없습니다. 그것은 내가 사용하려고하는 코드를 따른다. (스프링 MVC에 의해 나머지)

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

서버는 나에게 예외 Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: null

답변

5

실제 문제는 스레드 this에 설명 된대로 모듈 body-parserhttp-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); 
     // incase 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); 
    } 
} 

이 f ***** 문제로 2 일을 잃어 버렸습니다. 희망이 도움이됩니다!

+0

이렇게하면 '보낸 후 헤더를 설정할 수 없습니다.'오류가 발생합니다. Cf. https://github.com/nodejitsu/node-http-proxy/issues/1168 및 https://github.com/nodejitsu/node-http-proxy/issues/908. –

0

왜이 특급 체인을 사용하지 않는 줄? 첫 번째 기능에 은 같은 것을 할 : 당신은 그냥 미들웨어를 사용할 필요가

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

+0

먼저 body-parser를 체인화해야합니까? Beacuse 나는 그것이 요청을 소비하는 것으로 나타났습니다. –

+0

명시 적 구성에서 body-parser를 사용해야합니다 :'app.use (bodyParser.urlencoded ({extended : true})); \t app.use (bodyParser.json()); ' –

+0

요청을 사용하지 않습니까? 다음 미들웨어에서 사용할 수 있습니까? –

0

.

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

, 역할 기반 액세스 제어를 etc .....

특정 경로의 미들웨어도 사용할 수 있습니다.

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!!"); 
}); 
+0

apiProxy를 호출하기 전에 req.body를 로깅하여이 로그를 제공하십시오. –

관련 문제