skip to Main Content

am new to nodeJS am trying to post the collection when the button is been clicked, i don’t is posting because am getting an error:undefined, when i console the req.body please what am doing wrong here. is there something am not doing

Here’s my code.

//create.ejs file
<form action="/blogs" method="post">
                <div>
                    <label>Title</label>
                    <input name="title" type="text"/>
                </div>
                <div>
                    <label>Content header</label>
                    <input name="content" type="text"/>
                </div>
                <div>
                    <label>Content Body</label>
                    <textarea name="body"></textarea>
                </div>
                <div class="button">
                    <button>Post content</button>
                </div>
            </form>



//app.js file 
const express = require("express")
const app = express()
const mongoose = require("mongoose")
const Schema = mongoose.Schema;

const BlogPost = new Schema({
    title:{
        type: String,
        required: true
    },
    content: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    }
})

const Blog = mongoose.model("Blog", BlogPost)
module.exports = Blog;

app.post("/blogs", (req, res) => {
    const blogs = new Blog({
        title:req.body.title,
        content: req.body.content,
        body: req.body.body,
    })
    blogs.save()
    .then(result => console.log(result))
    .catch(err => console.log(err))
})

3

Answers


  1. Chosen as BEST ANSWER

    I forget to add urlencoded method.

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

  2. In the button element add

    <button type="submit">Post content</button>
    
    Login or Signup to reply.
  3. You must write

    <input type="submit" name="Post content" value="Post content">
    

    instead of this Post content

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search