在Nodejs POST请求中实现Recaptcha登录

时间:2019-01-10 08:49:42

标签: node.js request recaptcha

我想在我的登录表单上使用ReCaptcha。我已经能够添加它,但是每当您失败或选择验证码时,应用程序就会崩溃。我收到错误消息:

    throw new Error('Can\'t set headers after they are sent.');
    ^

    Error: Can't set headers after they are sent.

我很确定这是因为有多个请求/响应,但是我对NodeJS或Requests不够熟悉,无法找到另一种方法。

这是我的登录帖子请求代码。

app.post('/login', function(req, res) {
    req.session.email=req.body.loginemail;
    req.session.password=req.body.loginpass;

    if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {
        res.redirect('login');
            console.log("Select Captcha");
            errorCode = "Select Captcha";
            app.locals.errorCode = "Select Captcha"
      }
      var secretKey = "somekey";

      var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress;

      request(verificationUrl,function(error,response,body) {
        body = JSON.parse(body);
        if(body.success !== undefined && !body.success) {
            console.log("Failed Captcha");
        }
      });

    var logoptions = {
        url: 'https://someurl/login',
        headers: 
            {   'Postman-Token': 'sometoken',
                'cache-control': 'no-cache',
                'Content-Type': 'application/x-www-form-urlencoded' 
            },
        form: { email: req.body.loginemail, password: req.body.loginpass } };

    request.post(logoptions, function (error, response, body) {
        if (response.statusCode == 200){
            console.log(response);
        *other code related to login*
        }
    });
});

通常我会怎么做,因为我很确定自己的方式不正常。您是否不像我在此处一样提交表单,仅检查用户是否选择了验证码?

0 个答案:

没有答案