Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
How can I "encapsulate" this code into a module so it could become reusable?

I have got this Node.JS snippet and would like to write it as a module, so I can use recaptcha in different parts of my system.

This is how it currently looks like:

app.post('/register_user', (req, res) => {
  const secret_key = process.env.RECAPTCHA_SECRET;
  const token = req.body.recaptcha;
  const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;
  fetch(url, { method: "post",})
    .then((response) => response.json())
    .then((google_response) => {
      if (google_response.success == true) {      
        res.format({'text/html': () => res.redirect(303, '/register'),})
      } else {
        return res.send({ response: "Failed" });
      }
    })
    .catch((error) => {
      return res.json({ error });
    });
})

I have tried to write the following module which works absolutely great, but I have absolute no idea about how to call it from the app.post, since I always get undefined as return:

import fetch from 'node-fetch';

export function fetch_out(url, timeout = 7000) {
    return Promise.race([
        fetch(url),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('timeout')), timeout)
        )
    ]);
}
export async function checkRecaptcha(token, secret_key){
    const url = "https://www.google.com/recaptcha/api/siteverify?secret=" + secret_key + "&response=" + token;
    try{
    const response = await fetch_out(url, 1000);
    const google_response = await response.json();
    }catch(error){
        return error;
    }
    return google_response;
}

Any help would be appreciated! Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could make this method reusable by removing the framework actions that need to happen and only return if the validation was successful or not. This way, it will be reusable in another project that doesn't use a specific framework.

Example module;

export async function checkRecaptcha(token, secret_key) {
    const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;
    
    const response = await fetch(url, { method: "post",});
    if (!response.ok) return false;

    const json = await response.json();
    if (!json.success) return false;      
    
    return true;
}

Usage:

import { checkRecaptcha } from "./some-file-name";

app.post('/register_user', async (req, res) => {
    const isHuman = await checkRecaptcha(req.body.recaptcha, process.env.RECAPTCHA_SECRET);
    
    if (!isHuman) {
        return res.send({ response: "Failed" });
    }
    
    return res.format({'text/html': () => res.redirect(303, '/register'),});
});

If you specifically want to call an action after the validation, you can also use successful and error callbacks.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda