I'm trying to make a POST request with Express, but req.body result to be empty {}. I've tried with Postman, and it works. I noticed that the input fields after submit are correct so I can't figure out what the problem is. Attached you can find the code I've written for the POST request. Any suggestions on how to fix this? Thanks in advance!
<form id="formwork" encType="multipart/form-data" action="http://localhost:3000/new_work" method="post" novalidate>
<div >
<header >
<h2 >Inserisci il tuo workshop</h2>
<p>Fatti conoscere attraverso la nostra accademia!</p>
</header>
</div>
<div >
<br>
<div >
<span >
<i ></i>
</span>
<input id="nomework" name="nomework" type="text" placeholder="Nome workshop" required>
<br>
<br>
<br>
<span >
<i ></i>
</span>
<input id="tipologia" name="tipologia" type="text" placeholder="Tipologia workshop" list="tip" required>
<datalist id="tip">
<option>Fotografia</option>
<option>Videomaker</option>
<option>Postproduzione</option>
</datalist>
<div >
Devi definire la categoria del tuo workshop.
</div>
<br>
<br>
<br>
<span >
<i ></i>
</span>
<input id="datawork" name="datawork" type="datetime-local" placeholder="Data e ora workshop" required>
<br>
<br>
<br>
</div>
</div>
<div >
<button id="submit">Inserisci workshop</button>
</div>
</form>
app.post('/new_work', (req, res) => {
console.log("BODY: ",req.body); // empty body {}
const workshop = {
nome : req.body.nomework,
nomeutente : req.session.passport.user.username,
nomefotografo : req.session.passport.user.name,
cognomefotografo : req.session.passport.user.surname,
tipologia : req.body.tipologia,
data : req.body.datawork
};
vpa.insertWorkshop(workshop)
.then((result) => res.redirect("workshop.html"))
.catch((err) => res.status(503).json({ error: 'Errore db durante la registrazione del workshop'}));
});
CodePudding user response:
Try to add this middleware before your routes.
const express = require('express');
const app = express();
app.use(express.json()); // <---
There are a lot more detailed explained answers here on StackOverflow addressed to this question. Please research them first. You can see here.
CodePudding user response:
I think what you're missing is:
const express = require('express')
const app = express()
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded({ extended: true }));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
// other code below...