Home > database >  why is my form not post after using post method?
why is my form not post after using post method?

Time:12-06

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

CodePudding user response:

You must write

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

instead of this Post content

CodePudding user response:

In the button element add

<button type="submit">Post content</button>

CodePudding user response:

i forget to add urlencoded method.

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