2017-03-03 1 views
0

이 튜토리얼 (https://codeforgeek.com/2016/03/google-recaptcha-node-js-tutorial/)을 사용하여 Google recaptcha를 설정하고 자체 코드로 recaptcha 코드를 이동하려고합니다. 내가 얻을 : 콘솔에서res.json이 Node.js 모듈의 함수가 아닙니다.

 
TypeError: res.json is not a function 

이 코드하려고하면

var checkRecaptcha = function(req, res){ 
    // g-recaptcha-response is the key that browser will generate upon form submit. 
    // if its blank or null means user has not selected the captcha, so return the error. 

    if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) { 
     return res.json({"responseCode" : 1,"responseDesc" : "Please select captcha"}); 
    } 

    // Put your secret key here. 
    var secretKey = "************"; 

    // req.connection.remoteAddress will provide IP address of connected user. 
    var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress; 

    // Hitting GET request to the URL, Google will respond with success or error scenario. 
    var request = require('request'); 
    request(verificationUrl,function(error,response,body) { 

     body = JSON.parse(body); 
     // Success will be true or false depending upon captcha validation. 
     if(body.success !== undefined && !body.success) { 
      return res.json({"responseCode" : 1,"responseDesc" : "Failed captcha verification"}); 
     } 
     return res.json({"responseCode" : 0,"responseDesc" : "Sucess"}); 
    }); 
} 

module.exports = {checkRecaptcha}; 

왜 이런 일이 않습니다를? 나는 app.use(bodyParser.json());을 내 app.js에 설정하고 res.json()은 내 응용 프로그램의 다른 부분에서 제대로 작동하는 것처럼 보입니다. 다만이 recaptcha 모듈은 아닙니다.

+1

어떻게 당신이 보여준 모듈/미들웨어 포함/사용하고 있습니까? (또한'bodyParser.json()'은 * JSON 요청을 구문 분석하고 JSON 응답을 보내지 않음) – mscdex

+0

오류가 발생하는 특정 행이 있습니까? – jonathanGB

+0

@jonathanGB 7, 23, 25 번 줄에서 오류가 발생합니다 (Google recaptcha 응답에 따라 다름). –

답변

1

미들웨어 사용에 따라 res을 함수에 전달하지 않고 대신 콜백을 전달합니다 (및 checkRecaptcha()에는 요청에 직접 응답하므로 콜백 매개 변수가 없습니다).

대신이 시도 : 단순히

app.post('/login', function(req, res) { 
    var recaptcha = require('./recaptcha'); 
    recaptcha.checkRecaptcha(req, res); 
}); 

이상 :

app.post('/login', require('./recaptcha')); 
관련 문제