Currently, I am in the process of developing a small server and website using Express. At this point, my goal is to send a POST request to my Express server with basic credentials encoded as JSON.
The issue I am facing is that no matter what I attempt, the request body always ends up empty on the server side. While on the frontend side, I can verify that the values are present. My code successfully logs the correct username and password before sending the request. Additionally, when inspecting the network panel in Chrome dev tools, I can see the accurate payload being sent to the server.
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 also attempted to curl a straightforward POST request to my server. The curl command used:
curl -H POST "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/register
Surprisingly, even with the curl request, the request body in my server code came out empty. I suspect that the problem lies within the backend, although I remain uncertain. To confirm, I implemented requests using both curl and fetch methods.
Below is the Express code snippet 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 outcome constantly displays empty curly brackets in the result, whereas there should be a username and password included as shown in the previous requests. It's perplexing why it remains empty despite utilizing Express version 4.17 which supports express.json().
Additionally, I want to mention that previously when I employed an html form and encoded the data using application/x-www-form-urlencoded along with decoding it in my Express app with
app.use(express.urlencoded({ extended: true}))
it was successful. I received the username and password without any issues. However, now with JSON, the body arrives empty on the backend.
This situation has left me feeling quite frustrated.