Using ExpressJs, I have created a simple app that can handle post requests and form submissions. Below is the code snippet from my index.js file:
require ('./models/db');
const express = require('express')
const app = express()
const bodyParser = require('body-parser');
const hotelController = require('./controllers/hotelController');
app.use(express.static('public'))
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/', (req, res)=>{
res.sendFile(path.join(__dirname, public, 'index.html'));
})
app.listen(30001, () => console.log("listening on port 30001"))
app.use('/hotel', hotelController);
The controller file accepts POST requests, but I noticed that the request body is always empty, causing the code to break. Here is a snippet from the controller file:
const express = require ('express');
var router = express.Router();
const mongoose = require ('mongoose');
const Hotel = mongoose.model('Hotel');
router.post('/',(req, res)=> {
console.log(req.body)
try {
insertRecord(req,res);
} catch (error) {
console.log("An error occurred: " + error.message)
}
})
//some more code
module.exports = router;
Edit 1: See Postman screenshot https://i.sstatic.net/rowlm.png
Edit 2: After changing Content-Type to application/x-www-form-urlencoded in Postman, the request worked with a proper body. However, when submitting from the form, the body was empty again. Check out the code snippet from my messy index.html file for handling the form submission.
<form name="formInfo" autocomplete="off" enctype="application/x-www-form-urlencoded" >
<div class="form-group">
<label for="inputOwnerName">Name </label>
<input type="text" class="form-control" id="inputOwnerName" placeholder="Some name" value="Test Name" >
<div class="form-group" style="text-align: center;">
<button class="btn btn-yellow" style="width: 200px;">Send</button>
</div>
</form>
<script>
var form = document.forms.namedItem("formInfo");
form.addEventListener('submit', function(ev) {
var oData = new FormData(form);
var ownerName = document.getElementById("inputOwnerName").value;
oData.append("inputOwnerName", ownerName);
var oReq = new XMLHttpRequest();
oReq.open("POST", "/hotel", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
// Handle success
} else {
// Handle error
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
</script>