Thursday, 25 May 2017

Google Recaptcha v2 NodeJS

I am trying to verify my Google Recaptcha v2 in the backend in NodeJS.

validateRecaptchaRestriction is the function that I use in the middleware:

app.post('/contact', middleware.validateRecaptchaRestriction, routes.views.contact);

My Code:

var doReq = require("request");

function validateRecaptcha(userResponseToken) {
    doReq.post({url: 'https://www.google.com/recaptcha/api/siteverify', form: {data:{secret: '****************', response: userResponseToken}}}, function(err,httpResponse,body){ 
         return body && body.success;
    });
}

exports.validateRecaptchaRestriction = function(req, res, next) {
    if (!(req && req.body && req.body['g-recaptcha-response'] && req.body['g-recaptcha-response'].length)) {
        return res.json({
            "responseCode": 1,
            "responseDesc": "Please select captcha"
        });
    }

    if (validateRecaptcha(req.body['g-recaptcha-response'])) {
        next();
    } else {
        return res.json({
            "responseCode": 1,
            "responseDesc": "Failed captcha verification"
        });
    }
};

I always get "Failed captcha verification" if I submit the form although I have solved the captcha correctly. What is wrong with my request?



via SiriSch

No comments:

Post a Comment