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

468
Vistas
Display express.js res.send() without overwriting current html

I am trying to create a calculator app using express.js to get request for an html file and a post request that takes the user's input and responds with the answer. However, I want to display my answer inside a html container without the page redirecting. Is there a way to achieve this with vanilla javascript?

index.html

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="styles.css" />
    <link rel="shortcut icon" href="#" />
    <title>Calculator</title>
  </head>
  <body>
    <h1>Calculator App</h1>
    <form action="/" method="post" class="ajax">
      <label for="userInput">Enter Equation</label>
      <input type="text" id="equation" name="equation" />
      <button type="submit" id="btn_submit">Calculate</button>
    </form>
    <div class="container"></div>
  </body>
</html>

app.js

const express = require('express'); 
const app = express();
port = 3000;

app.use(express.urlencoded({ extended : false }));
app.use(express.static('public'));

app.get('/', (req, res) => {
    res.sendFile(__dirname + public);
});

app.post('/', (req, res) => {
    let equation = req.body.equation;
    console.log(equation);
    let result = eval(equation);
    res.status(200).send('Result is ' + result);
    
});

app.listen(port, ()=> {
    console.log('Hosted on port: ' + port);
});

CalculatorApp Evaluated Expression

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

0

You will need to write front end JavaScript code to make the ajax request instead of having the form action submit the request. The JavaScript will receive the response and can update the value on the HTML.

app.post('/', (req, res) => {
    let equation = req.body.equation;
    console.log(equation);
    let result = eval(equation);
    res.status(200).json({ value: `Result is ${result}` });
    
});

<script>  

 document.querySelector('form').addEventListener('submit',submitEquation);

    
        function submitEquation(event){
            event.preventDefault();
             const input = document.querySelector('#equation');
             const equation = input.value;
             const clearInput = true;
             if(clearInput){
                input.textContent = '';
             }
             fetch(window.location.origin, { 
                method: 'post', 
                body: JSON.stringify({ equation }) 
             })
             .then(response => response.json())
             .then(json => {
                  document.querySelector('.container').textContent = json.value;
             })
          }
</script>
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