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

170
Views
¿Cómo reenvío un objeto al backend desde el front-end?

Estoy tratando de comunicarme con el frontend al backend. actualmente, tengo el backend enviando una expresión al frontend, y el frontend la calcula. a partir de ahí, quiero que el frontend envíe la respuesta calculada al backend.

Por ejemplo: el backend envía "2+2=" el frontend calcula que 2+2 = 4 el frontend luego envía la respuesta 4 al backend el backend registra la respuesta 4

Interfaz

 var XMLHttpRequest = require('xhr2'); const URL = "http://localhost:5000/" let firstNumber = Math.floor(Math.random() * 10); let secondNumber = Math.floor(Math.random() * 10); const express = require('express'); const app = express(); // excecuting random addition const finalExpression = firstNumber + "+" + secondNumber + "=" console.log(finalExpression); var xhr = new XMLHttpRequest(); xhr.open("POST", URL, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify({ expression: finalExpression }))

back-end:

 const express = require('express') const app = express() app.use(express.json()) app.post('/', (req, res) => { console.log(req.body.expression); arr = req.body.expression.split("") console.log(parseInt(arr[0]) + parseInt(arr[2])) // res.send(parseInt(arr[0]) + parseInt(arr[2])) }) app.listen(5000, () => console.log())

como puede ver, probé res.send en el frontend al backend.

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

0

Parece que has mezclado un poco las cosas.

  1. No puede usar express en el front-end, es una aplicación de nodo. No debería necesitar usar XMLHttpRequest en el servidor. express manejará todo el enrutamiento por usted.

  2. Debe usar fetch en el front-end para obtener/publicar solicitudes en el servidor (he usado async/await aquí).

Podría parecerse un poco más a esto.

Servidor:

 // Send an expression to the front-end app.get('/getExpression', (req, res) => { res.send(expression); }); app.post('/postResult', (req, res) { const result = res.body; // Calculate whether the result is correct, // and then send the answer back res.send(isResultCorrect); });

Cliente:

 // To get the expression from the server const response = await fetch('/getExpression'); const expression = await response.text(); // To post the result back to the server const options = { type: 'POST', body: result }; const response = await fetch('/postResult', options); const isResultCorrect = await response.text();
about 4 years ago · Juan Pablo Isaza Report

0

Inviertes el frontend y el backend :) Es el frontend el que envía el XMLHTTPREQUEST y es el servidor el que procesa la solicitud y devuelve la respuesta.

Dicho esto, usar res.send es la solución correcta para devolver una respuesta. Hiciste lo correcto en BACKEND. Por lo tanto, puede descomentar // res.send(parseInt(arr[0]) + parseInt(arr[2])) y dejar el código de back-end como está.

Lo que falta en el FRONTEND es un código para escuchar y manejar esta respuesta:

 xhr.onreadystatechange = function() { if (xhr.readyState === 4) { console.log(xhr.response); } }

Agréguelo después de var xhr = new XMLHttpRequest();

Su código debería verse así:

 var xhr = new XMLHttpRequest(); // New code added here xhr.onreadystatechange = function() { if (xhr.readyState === 4) { // Handle the response (ex: console.log it) console.log(xhr.response); } } xhr.open("POST", URL, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify({ expression: finalExpression }))
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!