//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const { redirect } = require("express/lib/response");
const { forEach } = require("lodash");
const homeStartingContent = "Lacus vel facilisis volutpat est velit egestas dui id ornare. Semper auctor neq";
const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque..";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien.";
let posts = [];
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get("/", function(req, res){
res.render("home",{startingContent:homeStartingContent,posts:posts});
})
app.get("/about", function(req, res){
res.render("about",{aboutContent:aboutContent});
})
app.get("/contact", function(req, res){
res.render("contact ",{contactContent:contactContent});
})
app.get("/compose", function(req, res){
res.render("compose");
})
app.post("/compose", function(req,res){
const post = {
title:req.body.postTitle,
content:req.body.postBody
};
posts.push(post);
console.log(posts)
res.redirect("/");
})
app.get("/posts/:postName",function(req, res){
const requestedTitle = req.params.postName;
posts.forEach(function(post){
console.log(requestedTitle);
const storedTitle =req.body.postTitle;
console.log(storedTitle);
if(storedTitle===requestedTitle){
console.log("match found");
}
else{
console.log("Not a match");
}
});
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
I am having issue with app.get("/posts/:postName",function(req, res){
and const storedTitle =req.body.postTitle;
The issue is whenever I run http://localhost:3000/posts/Test in browser I am suppose to get output as match found but when I console log storedTitle to debug I get it as undefined istead of Test.
output screenshot:
output image
These are pictures of /compose ejs file.
compose.ejs
CodePudding user response:
Instead of const storedTitle =req.body.postTitle;
you should use const storedTitle = post.title;
CodePudding user response:
You get undefined
in log because, of the following lines:
const storedTitle =req.body.postTitle;
console.log(storedTitle);
Because, GET
requests does not have body
.
Change those lines as follows:
const storedTitle = post.title;
console.log(storedTitle);
I suppose it is a copy/paste error from /compose
handler :-)
Good day!
CodePudding user response:
You cannot use req.body
in a GET request
It should either use POST
app.post("/posts/:postName",....
or
const storedTitle =req.query.postTitle;