Home > Software design >  console.log () "cannot read values of undefined" error
console.log () "cannot read values of undefined" error

Time:08-03

I have written the following code to console.log the inputted value on the composed page, but it still gives undefined. Although the request gets posted and it logs any string statement like console.log("posted") but it is returning undefined if I try to log the inputted value. This is my app.js code

//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");

const homeStartingContent = "Lacus vel facilisis volutpat est velit egestas dui id ornare. Semper auctor neque vitae tempus quam. Sit amet cursus sit amet dictum sit amet justo. Viverra tellus in hac habitasse. Imperdiet proin fermentum leo vel orci porta. Donec ultrices tincidunt arcu non sodales neque sodales ut. Mattis molestie a iaculis at erat pellentesque adipiscing. Magnis dis parturient montes nascetur ridiculus mus mauris vitae ultricies. Adipiscing elit ut aliquam purus sit amet luctus venenatis lectus. Ultrices vitae auctor eu augue ut lectus arcu bibendum at. Odio euismod lacinia at quis risus sed vulputate odio ut. Cursus mattis molestie a iaculis at erat pellentesque adipiscing.";
const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Non diam phasellus vestibulum lorem sed. Platea dictumst quisque sagittis purus sit. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Mauris in aliquam sem fringilla. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Amet massa vitae tortor condimentum lacinia quis vel eros. Enim ut tellus elementum sagittis vitae. Mauris ultrices eros in cursus turpis massa tincidunt dui.";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";

const app = express();
var arr=[];
app.set('view engine', 'ejs');
app.get("/",function(req,res){
  res.render("home",{homecontent:homeStartingContent});
});
app.get("/contact",function(req,res){
  res.render("contact",{contactContent:contactContent});

});
app.get("/about",function(req,res){
  res.render("about",{aboutContent:aboutContent});

});
app.get("/compose",function(req,res){
  res.render("compose");

});
// here  is the function for post request on compose page giving undefined
app.post("/compose",function(req, res){

  console.log(req.body.composed);

});

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
This is my compose.ejs code

<%-include("partials/header");-%>
<h1>Compose</h1>

<form  action="/compose" method="post">
<input type="text" name="composed" >
<button type="submit" name="button">Publish</button>
</form>
<%-include("partials/footer");-%>

CodePudding user response:

This has nothing to do with console.log. It errors because req.body is undefined before it tries to pass that value to console.log.

Express attempts to run middleware and end points in the order that they are registered.

app.post("/compose",function(req, res){ runs and req.body is undefined then the request processing stops.

It never reaches app.use(bodyParser.urlencoded({extended: true})); because you defined it afterwards.

Change the order of your code so things that need to be executed first appear first.

CodePudding user response:

@Quentin is correct, I have reorganised your codes as below, you can create a "views" folder to put all the ejs files into it.

    const express = require("express");
    const bodyParser = require("body-parser");
    const ejs = require("ejs");

    const app = express();
    var arr = [];
    app.set("views", path.join(__dirname, "views"));
    app.set("view engine", "ejs");

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(express.static("public"));

    const homeStartingContent = "Lacus vel facilisis volutpat est velit egestas dui id ornare. Semper auctor neque vitae tempus quam. Sit amet cursus sit amet dictum sit amet justo. Viverra tellus in hac habitasse. Imperdiet proin fermentum leo vel orci porta. Donec ultrices tincidunt arcu non sodales neque sodales ut. Mattis molestie a iaculis at erat pellentesque adipiscing. Magnis dis parturient montes nascetur ridiculus mus mauris vitae ultricies. Adipiscing elit ut aliquam purus sit amet luctus venenatis lectus. Ultrices vitae auctor eu augue ut lectus arcu bibendum at. Odio euismod lacinia at quis risus sed vulputate odio ut. Cursus mattis molestie a iaculis at erat pellentesque adipiscing.";
    const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Non diam phasellus vestibulum lorem sed. Platea dictumst quisque sagittis purus sit. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Mauris in aliquam sem fringilla. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Amet massa vitae tortor condimentum lacinia quis vel eros. Enim ut tellus elementum sagittis vitae. Mauris ultrices eros in cursus turpis massa tincidunt dui.";
    const contactContent = "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";

    app.get("/",function(req,res){
    res.render("home",{homecontent:homeStartingContent});
    });

    app.get("/contact",function(req,res){
    res.render("contact",{contactContent:contactContent});
    });

    app.get("/about",function(req,res){
    res.render("about",{aboutContent:aboutContent});
    });

    app.get("/compose", function (req, res) {
      res.render("compose");
    });

    app.post("/compose", function (req, res) {
      console.log(req.body.composed);
      res.redirect("/");
    });

    app.listen(3000);
  • Related