2017-03-03 104 views
0

我試圖使用本教程設置Google Recaptcha(https://codeforgeek.com/2016/03/google-recaptcha-node-js-tutorial/),並將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.js中設置了app.use(bodyParser.json());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'));