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

132
Views
¿Cómo puedo usar la variable de cantidad fuera de esta función? ¿Alguien puede ayudarme?

¿Alguien puede decirme cómo puedo obtener la variable de cantidad o sus datos que estoy obteniendo de req.body fuera de esta función?

 app.post("/pay", (req, res) => { console.log(req.body); const { amount , description , name } = req.body; //this is that amount variable const create_payment_json = { intent: "sale", payer: { payment_method: "paypal", }, redirect_urls: { return_url: "http://localhost:3000/success", cancel_url: "http://localhost:3000/cancel", }, transactions: [ { item_list: { items: [ { name: name, sku: "001", price: amount, currency: "USD", quantity: 1, }, ], }, amount: { currency: "USD", total: amount, }, description: description, }, ], }; paypal.payment.create(create_payment_json, function (error, payment) { if (error) { throw error; } else { for (let i = 0; i < payment.links.length; i++) { if (payment.links[i].rel === "approval_url") { res.redirect(payment.links[i].href); } } } }); }); app.get("/success", (req, res) => { const payerId = req.query.PayerID; const paymentId = req.query.paymentId; const execute_payment_json = { payer_id: payerId, transactions: [ { amount: { currency: "USD", total: amount, // I want it here also }, }, ], }; paypal.payment.execute( paymentId, execute_payment_json, function (error, payment) { if (error) { console.log(error.response); ; } else { console.log(JSON.stringify(payment)); res.send("Success"); } } ); });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No está muy claro a partir de su pregunta, pero parece que solo desea tener acceso a la amount desde fuera de la devolución de llamada de respuesta. Si es tan simple como eso, solo necesita tener un lugar para ello en un ámbito superior. Por ejemplo, voy a almacenar todos los pagos en una matriz de payments . También estoy cambiando el nombre de "cantidad" a "cantidad" (está mal escrito).

Cada vez que se realiza un POST en app.post("/pay") , realizamos un pago. payments están disponibles para app.get("/success") porque está en un ámbito superior.

Si esto no es lo que está tratando de hacer, debe agregar más detalles a su pregunta y explicar exactamente lo que no funciona.

index.js

 import express from "express"; const app = express(); const payments = []; app.use(express.json()); app.get("/", (req, res) => { res.send("Hello world"); }); app.get("/success", (req, res) => { console.log(`There have been ${payments.length} payments`); if (payments.length) { const {person, amount, time} = payments[payments.length - 1]; console.log(`Last payment was ${amount} by ${person} @ ${time}`); } res.sendStatus(200); }); app.post("/pay", (req, res) => { const {person, amount} = req.body; const time = Date.now(); payments.push({person, amount, time}); console.log(`${person} paid ${amount} @ ${time}`); res.sendStatus(200); }); app.listen(3002, () => { console.log("Listening"); });

Este es el archivo que usé para probar. Utiliza node-fetch fetch un polyfill de búsqueda.

test.js

 import fetch from "node-fetch"; const sleep = (t=1000) => new Promise(r => setTimeout(r, t)); const main = async () => { const payResponse = await fetch("http://localhost:3002/pay", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ person: "Bob Barker", amount: 500 }) }); await sleep(); const checkResponse = await fetch("http://localhost:3002/success"); }; main() .then(() => console.log("Done")) .catch(err => console.error(err));

Ejecutarlo produce esto:

 Listening Bob Barker paid 500 @ 1631202912836 There have been 1 payments Last payment was 500 by Bob Barker @ 1631202912836
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!