0

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);

2 Answers 2

1

Change this:

app.use(bodyParser.json());

to this:

app.use(bodyParser.urlencoded({ extended: true}))

HTML forms do not send JSON data as a post request instead it sends application/x-www-form-urlencoded data which needs to be decoded by body parser.

Sign up to request clarification or add additional context in comments.

Comments

1

Have you created your mongoose post schema? If so, could you please post it here. You use the mongoose schema to create a new model, as shown in the example below:

    app.post("/person", async (request, response) => {
        try {
            var person = new PersonModel(request.body);
            var result = await person.save();
            response.send(result);
        } catch (error) {
            response.status(500).send(error);
        }
    });

If your node server is starting up, and you're able to post to mongo, mongoose/DAL layer may be causing the issue.

Here I think you can use a mongoose model instead, it looks like you have that commented out: // 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
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.