2017-03-03 75 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'));