2017-03-03 9 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')); 
関連する問題