Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

461
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda