Reputation: 417
I have this code js:
app.use(express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
app.get('/', function(req, res){
res.sendFile(__dirname+'index.html')
});
app.get('/ins.html', function(req, res){
res.sendFile(__dirname+'ins.html')
});
app.post('/ins', function(req, res){
console.log(req.body)
res.redirect('/')
});
And this code html:
<form method="post" enctype="multipart/form-data" action="/ins"><p> <strong>INSERISCI LA TUA CAGATA<br></strong>
<br><p>Username </p> <input type="text" name="username" required><br>
<br><p>Password  </p> <input type="password" name="password" required><br><br><br>
<input type="submit" class="mainBtn" id="submit" value="Inserisci Cagata">
<p>
</form></h2>
When i go to the page, in che console show "{}" and i have not access in the POST variable. how can i solve the problem?
Upvotes: 2
Views: 58
Reputation: 40914
You're using a different encoding than either of your body parsers support.
You're using multipart encoding (multipart/form-data
) in your form, but your server is expecting JSON (application/json
) or URL-encoded data (application/x-www-form-urlencoded
).
Unless you need to upload files (which require multipart encoding), you should use URL encoding (which is the defualt if enctype
is not specified). Then the body would be parsed correctly with the bodyParser.urlencoded()
parser:
<form method="post" enctype="application/x-www-form-urlencoded" action="/ins">
<!-- ^--- note the enctype -->
<p>
<strong>INSERISCI LA TUA CAGATA<br></strong>
<br>
<p>Username </p>
<input type="text" name="username" required>
<br>
<br>
<p>Password  </p>
<input type="password" name="password" required>
<br>
<br>
<br>
<input type="submit" class="mainBtn" id="submit" value="Inserisci Cagata">
</p>
</form>
If you do need multipart encoding (e.g., if you're uploading files), you can use a multipart body parser (such as multiparty or busboy). Note that because multipart is a complex encoding, you won't get req.body
directly, but you have to do some parsing yourself, which is why you should avoid multipart encoding unless you actually need it.
Upvotes: 4