0

So what I am trying to do is take data from a form and push it into my list as a map. It currently says

Cannot read property 'url' of undefined

express = require("express");
app = express();
var bodyParser = require("body-parser");
app.use(express.static("public"));
var imagedata = [
    {url: "...", description: "..."},
    {url: "...", description: "..."}
];
app.use(bodyParser.urlencoded({extended: true}));


app.get("/", function(req, res){
    res.render("home.ejs", {imagedata: imagedata});
});
app.post("/post", function(req, req){
    var NewPost = req.body.url;
    var Description = req.body.description;
    imagedata.push({url: NewPost, description: Description});
    res.redirect("/");

});
Barmar
  • 596,455
  • 48
  • 393
  • 495

3 Answers3

1

It's saying req.body is undefined because you defined both the request and response as req

Change app.post("/post", function(req, req) to app.post("/post", function(req, res)

Adam Neuwirth
  • 149
  • 1
  • 10
0

without seeing the client-side code (the form) I don't really see anything wrong with the code. Try adding console.log to /post:

express = require("express");
app = express();
var bodyParser = require("body-parser");
app.use(express.static("public"));
var imagedata = [
    {url: "...", description: "..."},
    {url: "...", description: "..."}
];
app.use(bodyParser.urlencoded({extended: true}));


app.get("/", function(req, res){
    res.render("home.ejs", {imagedata: imagedata});
});
app.post("/post", function(req, req){
    var NewPost = req.body.url;
    var Description = req.body.description;

    console.log("NewPost:", NewPost, "NewDescription:", Description);

    imagedata.push({url: NewPost, description: Description});

    console.log("imagedata:", imagedata);

    res.redirect("/");

});

to see what data is being given and what has happened to imagedata.

Coder100
  • 114
  • 1
  • 11
0

as mentioned the question is not really clear but maybe this is what you are looking for although i don't really see the use case for using map instead of an object in this instance. see this post on when to use a map here

express = require("express");
app = express();
var bodyParser = require("body-parser");
app.use(express.static("public"));
var imagedata = [
    {url: "...", description: "..."},
    {url: "...", description: "..."}
];
app.use(bodyParser.urlencoded({extended: true}));


app.get("/", function(req, res){
    res.render("home.ejs", {imagedata: imagedata});
});
app.post("/post", function(req, req){
    var NewPost = req.body.url;
    var Description = req.body.description;
    let map = new Map() 
    map.set('url', NewPost).set('description', Description)
    imagedata.push(map);
    res.redirect("/");

});
Henri De Bel
  • 145
  • 2
  • 5