Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
¿Cómo puedo "encapsular" este código en un módulo para que pueda volverse reutilizable?

Tengo este fragmento de Node.JS y me gustaría escribirlo como un módulo, para poder usar recaptcha en diferentes partes de mi sistema.

Así es como se ve actualmente:

 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 }); }); })

He intentado escribir el siguiente módulo que funciona absolutamente bien, pero no tengo ni idea de cómo llamarlo desde app.post, ya que siempre obtengo un valor indefinido como retorno:

 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; }

¡Cualquier ayuda sería apreciada! ¡Gracias!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede hacer que este método sea reutilizable eliminando las acciones del marco que deben ocurrir y solo regresar si la validación fue exitosa o no. De esta forma, será reutilizable en otro proyecto que no utilice un framework específico.

Módulo de ejemplo;

 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; }

Uso:

 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'),}); });

Si desea llamar específicamente a una acción después de la validación, también puede usar devoluciones de llamada exitosas y de error.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!