Reputation: 55
I am building a simple financial app to practice my newbie JS skills. The client is running on localhost:3000 and the server is running on localhost:4001.
Client-side code:
async function addTransaction(id, date, description, header, amount) {
await fetch('http://localhost:4001/transactions', {
method: 'POST',
body: JSON.stringify({id, date, description, header, amount})
});
}
Server-side code:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 4001;
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
function addTransaction(req, res) {
console.log(req.body);
}
app.post('/transactions', addTransaction);
app.listen(PORT, () => console.log(`Listening on port ${PORT}...`));
I am aware that similar questions have been asked on this forum, but none of the given solutions, like adding Content-type: application/json
to the header have worked for me.
Interestingly, making a post request from Postman is actually working.
I hope anyone can help.
Upvotes: 0
Views: 850
Reputation: 943214
You failed to set a Content-Type
request header so the default is being applied (text/plain
IIRC).
Since the client hasn't said it is sending JSON, it doesn't trigger the JSON body parser you set up.
fetch('http://localhost:4001/transactions', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({id, date, description, header, amount})
});
Since that will turn the request into a preflighted request, you'll also need to configure your server to handle the preflight OPTIONS request before the client will make the POST request.
Currently you are rolling your own CORS handling:
app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); next(); });
Don't do that. Use the cors
middleware module and follow the instructions to configure it for preflighted requests.
Upvotes: 1