我正在尝试做的是防止用户绕过验证码。现在,在联系表单上,用户可以填写除验证码以外的所有字段,并让表单仍提交

这是显示联系表格的网页->
这是页面-> http://ec2-52-5-104-185.compute-1.amazonaws.com/contact

这是显示此联系表单的代码->

{{# autoForm schema='ContactSchema' id="contactForm" type="method" meteormethod="sendContact"}}
    {{> afQuickField name="categoryId"}}
    {{> afQuickField name="email" }}
    {{> afQuickField name="title" }}
    {{> afQuickField name="message" rows=8 }}

    <!-- googles reCaptcha , i'm using ayue:recaptcha  package to render this captcha -->
    {{> reCAPTCHA}}
{{/ autoForm }}


这是客户端JS流星要求的验证码

Template.contact.events({
    'submit form': function(e) {
        e.preventDefault();

        var formData = {
            //get the data from your form fields
        };

        //get the captcha data
        var recaptchaResponse = grecaptcha.getResponse();

        Meteor.call('formSubmissionMethod', formData, recaptchaResponse, function(error, result) {
            if (error) {
                console.log('There was an error: ' + error.reason);
            } else {
                console.log('Success!');
            }
        });
    }
});


这是从联系人表单中获取sendContact方法以及recaptcha meteor.call方法的服务器端代码。

Meteor.methods({
    formSubmissionMethod: function(formData, recaptchaResponse) {

        var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(recaptchaResponse, this.connection.clientAddress);

        if (!verifyCaptchaResponse.success) {
            console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
            throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
        } else {
            console.log('reCAPTCHA verification passed!');
        }

        //do stuff with your formData

        return true;
    },

    sendContact: function (doc) {
        check(doc, ContactSchema);

        var html = "<b>" + doc.title + "</b><br>"
        + "<b>" + doc.email + "</b><br><br>"
        + doc.message.escape();

        this.unblock();

        Email.send({
            to: orion.dictionary.get('contact form.email') && doc.categoryId,
            from: orion.config.get('MAIL_FROM'),
            // subject: orion.dictionary.get('global.siteName') + ' - Contact',
            subject: doc.title + ' - Contact',
            replyTo: doc.email,
            html: html
        })
    }
});

最佳答案

与其在服务器端方法上抛出错误,不如返回成功值,例如:

verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, doc.gRecaptchaResponse);

  if (verifyCaptchaResponse.data.success === false) {
    return verifyCaptchaResponse.data;
  }


比回调中的客户端要多,请执行以下操作:

if (result && result.success === false) {
      //CAPTCHA failed
      Modal.show('recaptcha');
    }
return false;


与其使用“提交表单”事件,不如使用AutoForm.hooks,然后对您的表单使用AutoForm.hooks中的onSubmit方法。

09-25 16:46