node.jsrecaptchaaxios

Google Recaptcha not working with axios


I am encountering an error while trying to verify my recaptcha witch axios

try{
            let result = await axios.post(
                'https://www.google.com/recaptcha/api/siteverify',
                {
                    secret: '6LcarRkTAAAAAPDNrruugUg1fJqOJnH-uvVa5KIL',
                    response: response
                },
                {
                    headers: {
                        "Content-Type": "application/json"
                    }
                });

            let data = result.data || {};
            if(!data.success){
                throw({
                    success: false,
                    error: 'response not valid'
                })
            }
        }catch(err){
            console.log(err);
            throw err.response ? err.response.data : {success: false, error: 'verifyCatpcha Error'}
        }

I am always getting the error

{ success: false,
'error-codes': [ 'missing-input-response', 'missing-input-secret' ] }

I tried it with postman and it works fine. Something wrong with my header?


Solution

  • You need to add one more key to your request: secret. The error message is caused by missing response and secret parameters when sending POST request.

    UPDATE: The POST params in the doc are not JSON, they must be passed as query string. That's why the error says it's missing both missing-input-response and missing-input-secret

    axios.post(
      `https://www.google.com/recaptcha/api/siteverify?secret=${secret}&response=${response}`,
      {},
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
        },
      },
    );
    

    Reference: Doc