2014-11-17 4 views
1

이것은 매우 간단한 질문 일 뿐이지 만 한 시간 이상 인터넷 검색을 해본 결과 아무 것도 찾을 수 없었습니다. 나는 또한 요청 객체를 인쇄 해 보았고, 유용한 것을 보지 못했다.grunt-contrib-connect 요청 개체에서 데이터 가져 오기

grunt-contrib-connect 미들웨어 정의 내에서 클라이언트 요청의 데이터 또는 본문을 얻으려면 어떻게해야합니까?

connect: { 
    main: { 
    options: { 
     hostname: "0.0.0.0", 
     port: 8080, 
     /** 
     * These are the mocked out backends for various endpoints 
     */ 
     middleware: function(connect, options, middlewares) { 
     middlewares.unshift(function(req, res, next) { 
      if (req.url !== '/v1/accounts/_findEmail') { 
      return next(); 
      } 

      // ******** 
      // How do I get the data content of the request? 
      var data = req.data; // Is undefined 
      // ******** 

      if (data && data.email === '[email protected]') { 
      res.writeHead(200, {"Content-Type": "application/json"}); 
      res.write(JSON.stringify({email:"found"})); 
      } else { 
      res.writeHead(404, {"Content-Type": "application/json"}); 
      res.write(JSON.stringify({email:"not found"})); 
      } 

      res.end(); 
     }); 

     return middlewares; 
     } 

    } 
    } 
} 

답변

2

그래서이 작업을 수행하는 데 필요한 몇 가지 사항이 있습니다.

here과 같이 connect는 기본적으로이 경우 NodeJS를 감싸는 것으로 추측해야합니다. 따라서 요청 객체는 실제로 http.ServerRequest이며 같은 방식으로 사용해야합니다.

따라서 var data = req.data; 대신에 req.on('data', function (data) { //do stuff });과 같은 콜백을 추가하고 데이터를 그렇게 볼 수 있습니다.

그 외에도 데이터를 읽기 전에 16 진수 배열이 아닌 문자열로 나오기 위해 req.setEncoding('utf8');을 추가해야했습니다.

connect: { 
    main: { 
    options: { 
     hostname: "0.0.0.0", 
     port: 8080, 
     /** 
     * These are the mocked out backends for various endpoints 
     */ 
     middleware: function(connect, options, middlewares) { 
     middlewares.unshift(function(req, res, next) { 
      if (req.url !== '/v1/accounts/_findEmail') { 
      return next(); 
      } 

      req.setEncoding('utf8'); 
      req.on('data', function (rawData) { 
      var data = JSON.parse(rawData); 

      if (data && data.email && data.email === '[email protected]') { 
       res.writeHead(200, {"Content-Type": "application/json"}); 
       res.write(JSON.stringify({email:"found"})); 
      } else { 
       res.writeHead(404, {"Content-Type": "application/json"}); 
       res.write(JSON.stringify({email:"not found"})); 
      } 

      res.end(); 
      }); 
     }); 

     return middlewares; 
     } 

    } 
    } 
} 
+0

게시 해 주셔서 감사합니다. 시간을 절약 해 줬어! Btw, 그것은 나를 위해 일했다 req.setEncoding ('utf8'); –

0

내가 그것을 설명 할 수 있지만 @ static416로 솔루션은 더 이상 나를 위해 작동하지 않았다

그래서 최종 해결책처럼 보인다. 그래서 새로운 것을 만들었습니다.

먼저 npm 패키지 body-parser를 설치하고 가져옵니다. 둘째, 미들웨어이 추가 :

module.exports = function(grunt) { 
    var bodyParser = require('body-parser'); 
    ... 
} 

지금 당신은 당신의 미들웨어 내부 req.body를 사용하여 데이터에 액세스 할 수 있습니다.

middleware: function(connect, options, middlewares) { 
      // inject a custom middleware into the array of default 
      middlewares.unshift(
       bodyParser.urlencoded({extended: true}), 
       bodyParser.json(), 
       function(req, res, next){ 
       // use data from post request 
       console.log(req.body); 
       next(); 
       }, ... 
     ) 
}, ...