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

386
Visualizações
Fetch does not POST from the Client-Side to the Server-side (Node.js)

Problem: I am using the following code provided by StackOverflow members. I like the code, and I wish it worked, but it did not, as I will explain:

The Purpose: Take input from the Client-Side, modify it with JavaScript, then POST the modified variables to the Server-Side (Node.js/Express).

The Code (credit to kwh):

<body>
  <script type="text/javascript">
    function customSubmit() {
      const name = document.getElementById('name').value + ' mock';
      const city = document.getElementById('city').value + ' mock';
      fetch('/posty', {
        method: 'POST',
        body: JSON.stringify({ name, city })
      })
    }
  </script>
  <form onsubmit="event.preventDefault(); customSubmit()">
    <label for="name">Name: </label>
    <input id="name" name="name" type="text">

    <label for="city">City: </label>
    <input id="city" name="city" type="text">

    <button type="submit">submit</button>
  </form>  
</body>

I have node.js and express.js serverside, and I have not installed node-fetch. I use EJS as templating engine/file for HTML and JS for the Client-Side.

Client side code:

app.post('/posty', (req,res) => {

    console.log(req.body)
 
})

which returns an empty object in the console (Linux terminal):

{}

Now if I replace the following line in the code:

<form onsubmit="event.preventDefault(); customSubmit()">

with

<form action="/posty" method ="POST">

I will get a non-empty object in the console:

{ name: 'John', city: 'Berlin' }

However, this is not the solution because I have to modify the person's name and the city before POSTing it to the Server-Side (Node.js).

Discussion:

I have not installed node-fetch for node.js. Even, If I installed it, I would have to import the module in a node.js server file that runs on the Server-Side, not on the Client-Side. I cannot see the point of installing node-fetch on node.js to use fetch() to POST in HTML/JS code running on a compatible browser on the Client-Side.

Maybe something is missing in the given codes above, either on the Server-Side or Client-Side, or both. I would appreciate it if someone could point that out. Also, I want to thank kwh, who provided the clean and compact code and helped organize my research to solve the problem.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Did you use parsed the body before your routes? You can do it with express.json()

app.use(express.json())
app.post('/posty', (req,res) => {

    console.log(req.body)
 
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Thanks for your responses. I find the solution with the help of two StackOverflow members and one of the other posts on StackOverflow forum:

I had to add the following line to fetch() block in the code that kwh suggested (Client-Side):

headers: new Headers({ "Content-Type": "application/json" })

Also, I added the following line to the code on the Server-Side as Ifaruki suggested:

app.use(express.json())

So one line of code was missing on the Server-Side and one on the Client-Side. I needed both.

Thanks again for your fast response and your help.

about 4 years ago · Juan Pablo Isaza Relatório

0

javascript is much faster than the dom, thats why you need to let the browser to render the dom first then to exec the js. it is done by this

document.addEventListener("DOMContentLoaded", function (event) {
  // content is loaded
  
  const form = document.getElementById("id-of-yow-form");
  form.addEventListener("submit", function (event) {
     event.preventDefault();
     //add yow code
  });

});

make sure to add the same id to yow form tag

 <form id="id-of-yow-form">
    <label for="name">Name: </label>
    <input id="name" name="name" type="text">

    <label for="city">City: </label>
    <input id="city" name="city" type="text">

    <button type="submit">submit</button>
  </form>  
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