1

I develop a Contact-Us page with Google ReCaptcha V2, After fill-up the form and take up the challenge of captcha and hitting the submit button I've got an error with [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client and it will not redirect to thank you page.

This my Code

app.post('/contact-us', (req, res) => {
console.log('req.body', req.body)
if (req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {
    res.send({success: false, msg: 'Please select captcha first'});
    return;
}
const secretKey = 'MY_SECRET_KEY';
const verificationURL = `https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${req.body['g-recaptcha-response']}&remoteip=${req.connection.remoteAddress}`;

https.get(verificationURL, (resG) => {
    let rawData = '';
    resG.on('data', (chunk) => { rawData += chunk })
    resG.on('end', function() {
        try {
            var parsedData = JSON.parse(rawData);
            if (parsedData.success === true) {
                return res.header("Content-Type", "application/json").send(body);
                
            } else {
                return res.send({success: false, msg: 'Failed captcha verification'});
                
            }
        } catch (e) {
            return res.send({success: false, msg: 'Failed captcha verification from Google'});
            
        }
    });
});
res.render('pages/thank_you', {title: 'Contact Us', menu_contact_us: 'active', pageClass: 'contact_us'})
Dave Dev
  • 23
  • 5

0 Answers0