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

48
Visualizações
how to get the data from a request in Express

I want to build a login page for my web app and I want to send data to my express server using fetch but when I log the req to the console the "req.body" is an empty object even if I sent an object with name and password properties can anyone help

client_side code:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="text" id="name" name="name" />
<input type="password" id="password" name="password" />
<button onclick="send()">login</button>
<script>
    async function send() {
        let name = document.getElementById('name').value
        let password = 
    document.getElementById('password').value

        let res = await 
 fetch('http://localhost:3000/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name,
                password                    
            })
        })
        if(res.redirected) {
            window.location.href = "/chat"
            localStorage.setItem('name', name)
            localStorage.setItem('password', password)
        } else {
            alert('not correct :P')
        }
    }
    </script>
   </body>          
   </html>   

server_side code:

app.use(express.urlencoded({ extended: true })); 

app.post('/api/login', (req, res) => {
  console.log(req.body)
  // why the output is an empty object {}
  res.redirect('/login')
})

I am a frontend dev and am new to backend #edit: my server code was app.post() but I accidentally put app.get() #because I rewrite the server code not paste it

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

0

Try app.post instead of app.get. See https://expressjs.com/en/guide/routing.html

Your javascript is performing an HTTP POST request, but express is only handling an HTTP GET request.

about 4 years ago · Juan Pablo Isaza Relatório

0

  1. Try to install and use body-parser
  2. Change app.get() to app.post(). But it will be right to use .put() if you processing /login path.
about 4 years ago · Juan Pablo Isaza Relatório

0

First, change app.get to app.post to handle the post request.

Second, add the built-in JSON body parser to properly add the "body" property to the request object. app.use(express.json())

To more robustly handle authentication, use passportjs.

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