I'm trying to redirect using res.redirect()
function. When I submit the form it should insert the data into the database and redirect me to home root. But the later is giving me this error:
Cannot POST /
this is my entire js file
const express =require("express");
const mongoose =require("mongoose");
const app=express();
const path=require("path")
const bodyparser= require("body-parser");
const Blog = require("./model/schema");
const { findById } = require("./model/schema");
app.use(express.static("public"));
app.set("views",path.join(__dirname "/views"));
app.set("view engine","ejs");
app.use(bodyparser.urlencoded({extended:true}));
mongoose.connect("mongodb://127.0.0.1:27017/blogdb", {useNewUrlParser: true, useUnifiedTopology: true })
.then(()=>
{
console.log("Connection successful!");
})
.catch(err=>
{
console.log("Error: connection failed")
})
app.get("/",async(req,res)=>
{
const blogs=await Blog.find({});
//console.log(blogs);
res.render("blogdata/show",{blogs});
})
app.get("/create",async(req,res)=>
{
// const id=req.params["id"];
// const eblog= await Blog.findById(id);
res.render("blogdata/form");
})
app.post("/create",async(req,res)=>
{
await Blog.insertMany([
{name:req.body.author,blog:req.body.blogcontent}
])
res.redirect("back");
})
app.listen(3000,()=>
{
console.log("Server is up and running");
})
This is all the file I have enter image description here HTML form
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/formstyle.css">
<meta charset="utf-8" />
<title>create blog</title>
</head>
<body>
<div><h1><b>Create your own blog!</b></h1></div>
<div >
<form action="/create" method="post">
<div >
<label for="name">Author</label>
<br>
<input type="text" id="name" name="author" value="">
</div >
<div >
<label for="para">Enter your blog</label>
<br>
<textarea name="blogcontent" id="para" cols="30" rows="10"></textarea>
</div>
<button type="submit" id="btn">Submit</button>
<!-- <label for="text">Edit your blog</label>
<input name="text" id="text"
type="text"
value= "" > -->
</form>
</div>
</body>
</html>
Please mention why this is happening and is there any better way to do this?
CodePudding user response:
Well, you have an endpoint /create
for the POST
method, but the error says that you're trying to send the form to /
on POST
.
Make sure in your form that you add the correct url
(meaning to add /create
)