我正在尝试使用本教程(https://codeforgeek.com/2016/03/google-recaptcha-node-js-tutorial/)设置google recaptcha,并将recaptcha代码移动到它自己的模块中。我明白了:
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()
似乎在我的应用的其他部分工作正常,而不是这个重新接收模块。
答案 0 :(得分:1)
根据您对中间件的使用情况,您没有将res
传递给函数,而是回调(而checkRecaptcha()
没有回调参数,因为它直接响应请求)。
请改为尝试:
app.post('/login', function(req, res) {
var recaptcha = require('./recaptcha');
recaptcha.checkRecaptcha(req, res);
});
或更简单:
app.post('/login', require('./recaptcha'));