A couple of issues in your code.
#1 In html,
Incorrect Content-Type Header
From
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
To
headers: {
"Content-Type": "application/json",
}
#2 In server.js,
The issue with your original server.js file not sending a 200 OK response was due to how your Express server handled the POST request.
res.status(200).json({ message: "Request received", data: req.body });
Here are full code update base on your code
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="post-btn">I'm a button</button>
<div id="response-message" style="margin-top: 10px; font-weight: bold;"></div>
<script>
const button = document.getElementById('post-btn');
const responseMessage = document.getElementById('response-message');
button.addEventListener('click', async () => {
try {
const test = {
key: 5
};
const response = await fetch('http://127.0.0.1:8080/example_post', {
method: "POST",
body: JSON.stringify(test),
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Completed!', data);
// Display the returned message in the HTML
responseMessage.textContent = `Message: ${data.message}, Data: ${JSON.stringify(data.data)}`;
} catch (err) {
console.error(`Error: ${err}`);
responseMessage.textContent = `Error: ${err.message}`;
}
});
</script>
</body>
</html>
server.js
import express from 'express';
import cors from 'cors';
// Making an app with express
const app = express();
// Enable CORS for all routes
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// POST request handler for "/example_post"
app.post("/example_post", async (req, res) => {
console.log("ping");
console.log(req.body);
// Send a 200 OK response with a success message
res.status(200).json({ message: "Request received", data: req.body });
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Problem');
});
// Start the server
app.listen(8080, () => {
console.log("Server up on http://localhost:8080");
});
package.json
{
"type": "module",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
run result
