Using the new noCAPTCHA reCAPTCHA with Node.js and Express
Using the new noCAPTCHA reCAPTCHA with Node.js and Express
Google recently released a new version of reCAPTCHA that eliminates typing for many users. Here's a quick how-to for integrating it in your Node.js application.
We're going to use Express for simplicity, but these steps are mostly agnostic and could be wrapped into any application.
Step 1: Register your site
Head over to the reCAPTCHA site and add your website to the list. You'll be presented with a screen like this:
Copy down the secret and site keys, you'll need them soon.
Step 2: Integrate it
Build out a basic Node.js application. The key point is that your HTML view will contain the div listed on the reCAPTCHA settings page, along with the reCAPTCHA client-side JavaScript. On the server, a function similar to the following is needed to verify the submitted claim with the reCAPTCHA server:
function verifyRecaptcha(key, callback) {
https.get("https://www.google.com/recaptcha/api/siteverify?secret=" + SECRET + "&response=" + key, function(res) {
var data = "";
res.on('data', function (chunk) {
data += chunk.toString();
});
res.on('end', function() {
try {
var parsedData = JSON.parse(data);
console.log(parsedData);
callback(parsedData.success);
} catch (e) {
callback(false);
}
});
});
}
Here's an example:
{ | |
"name": "nodejs-recaptcha", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"consolidate": "^0.10.0", | |
"express": "^4.10.4", | |
"hogan.js": "^3.0.2" | |
} | |
} |
In this case, we're using a normal form submit to carry over the CAPTCHA data and perform the registration. More and more web applications are becoming single-page JavaScript applications, though, so using an AJAX API to perform registration would be preferred. Here's a quick and dirty example of how you
would handle that scenario:
All in all, it's pretty simple, and worked well in my tests. I'll be sure to integrate this into some of my upcoming projects, now that both integrating and solving CAPTCHAs has become very easy.
If you have any questions or concerns about it, feel free to drop a note in the comments.
Comments
Post a Comment