Despite I set body-parser middleware, the form is sending empty request body . I'm using Pug as template engine. Mongo db and server connections are fine and app is running without errors, but when I hit form submit button, browser is still waiting for localhost and console.log(req.body)
is showing undefined value cuz of empty req body. Any ideas what is going on?
Here is my code:
const express = require("express");
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const path = require('path');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
MongoClient.connect('mongodb://localhost:27017/video', (err, db) => {
console.log("Connected to mongodb");
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
app.get('/', (req, res, next) => {
db.collection('movies').find({}).toArray((err,docs) => {
res.render('layout', { movies: docs });
});
});
app.post('/add', (req, res, next) => {
console.log(req.body.title);
res.redirect('/')
})
app.listen(3000, () => {
console.log("Server is running...")
});
});
form(action="/add", method="POST")
div.form-group
label(for='name') Title:
input#name.form-control(type='text', placeholder='Movie title')
label(for='year') Year:
input#year.form-control(type='text', placeholder='Production year')
label(for='link') Title:
input#link.form-control(type='text', placeholder='IMDB link')
input(type="Submit" value="Save →" class="btn btn-success")
via Wojciech Jeleń
No comments:
Post a Comment