Search code examples
javascriptjsonexpressbackendfetch-api

JSON Request body always empty in Express server


I am building an small server and web site with express. Right now I want to send a POST request to my express server with simple credentials encoded as JSON.

My Problem is no matter what I try, my request body is always empty on the server side. I am sure in the Frontend side the values are there, my code console.logs the correct username and password before sending the request. And I can see the correct payload sent to the server in the network panel of Chrome dev tools.

Frontend code:

<script>

    const username_input = document.getElementById('username');
    const password_input = document.getElementById('password');
    const submit_registration = document.getElementById('submit_registration');
    
    
    submit_registration.addEventListener('click', (event) => {
        const username = username_input.value;
        const password = password_input.value;
        console.log(username, password);
        
        fetch('/register', {
            method: 'POST',
            header: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                'username': username,
                'password': password
            })
        })
        .then(raw_response => raw_response.json())
        .then(response => console.log(response))
        .catch(err => console.log(err))
        
    });
</script>

I have also tried to curl a simple POST request to my server. The curl I used:

curl -H POST "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/register

The Request body in my server code was again empty. I guess the Issue lies somewhere in the Backend but I am not sure, so I added the Requests via curl and fetch just to be sure. Here is my express code for handling POST requests:

const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());

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

    console.log(req.body);
    res.status(200).send('Ok');

});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
});

The result is always empty curly brackets, but there suppose to be username & password in it like send in the Requests above and I don't get why it is always empty. My Express version is 4.17 so express.json() should work.

I have to add that when I used a html form and encoded the data via application/x-www-form-urlencoded and decoded it in my express app with

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

it worked. I received username and password, but now with json the body is always empty on the backend side.

I am very frustrated


Solution

  • Change the header property to headers in your fetch request.