I have a form in my node.js app and I want to take the data from the input fields and send it via POST. The post endpoint works, I tested it with Postman, but when I fill the form it just sends an empty object to the database without the form field information, how can I achieve this? Here is my ejs form:
<h1>Create a new post!</h1>
<form action="/post" method="POST">
<div>
<label for="title">Title</label>
<input type="text" id="title" name="title" required>
</div>
<div>
<label for="content">Post Content</label>
<input type="text" id="content" name="content" required>
</div>
<div>
<label for="categories">Categories</label>
<input type="categories" id="categories" name="categories" required>
</div>
<div>
<label for="date">Date</label>
<input type="text" id="date" name="date" required>
</div>
<div>
<label for="picture">Picture</label>
<input type="text" id="picture" name="picture" required>
</div>
<button type="submit">Create Post!</button>
</form>
and my server.js:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const BASE_URL = process.env.BASE_URL;
const PORT = process.env.PORT || 1337;
// let Post = require('./models/post.model.js');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect(BASE_URL, { useNewUrlParser: true, useUnifiedTopology: true })
const connection = mongoose.connection;
connection.once('open', function () {
console.log('Connection to MongoDB established succesfully!');
});
app.set('view-engine', 'ejs');
app.get('/', async (req, res) => {
res.render('index.ejs');
});
app.get('/', async (req, res) => {
res.render('login.ejs');
});
app.get('/post', async (req, res) => {
res.render('post.ejs');
});
app.post('/post', async (req, res) => {
let collection = connection.collection("posts_with_tags_test");
res.setHeader('Content-Type', 'application/json');
// let post = new Post(req.body);
let post = {
title: req.body.title,
postContent: req.body.content,
categories: req.body.categories,
date: req.body.date,
picture: req.body.picture
}
collection.insertOne(post)
.then(post => {
res.status(200).json({ post })
console.log(post.title)
})
.catch(err => {
res.status(400).send('failed')
});
})
app.listen(PORT);
and here is my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Post = new Schema({
title: {
type: String
},
postContent: {
type: String
},
categories: {
type: Array
},
date: {
type: String
},
picture: {
type: String
}
});
module.exports = mongoose.model('Post', Post);