Home > Back-end >  how to get the data from a request in Express
how to get the data from a request in Express

Time:10-08

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.get('/api/login', (req, res) => {
  console.log(req.body)
  // why the output is an empty object {}
  res.redirect('/login')
})

CodePudding user response:

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.

CodePudding user response:

  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.

CodePudding user response:

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.

  • Related