ValidationError:不允许使用“g-recaptcha-response”

时间:2018-01-30 10:40:52

标签: javascript node.js validation express joi

我想验证我的注册页面,我正在使用Joi validation除google recaptcha之外的所有工作正常。

以下是表单验证代码段的代码,

var UserSchema = Joi.object().keys({
    name: Joi.string().required(),
    username: Joi.string().alphanum().min(4).max(30).required(),
    email: Joi.string().email().required(),
    mobile: Joi.string().required(),
    password: Joi.string().regex(/^[a-zA-Z0-9]{8,30}$/),
    confirmationPassword: Joi.any().valid(Joi.ref('password')).required(),
    access_token: [Joi.string(), Joi.number()],
    recaptcha : Joi.string()    
});

发布注册页面请求

router.route('/register')
    .get(isNotAuthenticated, (req, res) => {
        res.render('register');
    })
    .post(async (req, res, next) => {
        try {
            const data = Joi.validate(req.body, UserSchema);
            if (data.error) {
                req.flash("error", "Enter Valid data");
                console.log(data.error);
                res.redirect('/register');
                return;
            }
            const user = await User.findOne({ username: data.value.username });
            if (user) {
                req.flash('error', 'Username already taken');
                res.redirect('/register');
                return;
            }
            if (req.body.captcha === undefined ||
                req.body.captcha === '' ||
                req.body.captcha === null) {
                res.redirect('/register');
                return;
            }
            const secretKey = '';
            const verifyUrl = `https://google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${req.body.captcha}&remoteip=${req.connection.remoteAddress}`;
            request(verifyUrl, async (err, response, body) => {
                try{
                    body = JSON.parse(body);
                    console.log(body);
                    if (body.success !== undefined && !body.success) {
                        res.redirect('/register');
                        return;
                    } else {
                        const newUser = await new User(data.value);
                        console.log('newUser', newUser);
                        await newUser.save();
                    }
                }catch(e){
                    throw e;
                }

            });  
            req.flash('success', 'Please check your email.');
            res.redirect('/login');
        } catch (error) {
            next(error);
        }
    });

当我点击提交时,我在控制台中收到了{ ValidationError: "g-recaptcha-response" is not allowed

的错误消息

1 个答案:

答案 0 :(得分:0)

我知道这篇文章是前一阵子的,但是我遇到了相同(或至少相似)的问题,解决方案是仅使用括号表示法访问g-recaptcha-response。因此,在您的Joi模式中,属性应如下所示:

["g-recaptcha-response"]: Joi.string().required();

我希望这对Google搜索错误的人有所帮助:D