Guide on Adding a Map to a List in JavaScript

Currently, I am trying to extract data from a form and add it as a map to my list. However, an error message is displayed:

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("/");
});

Answer №1

The error message indicates that the variable req.body is not defined, likely due to both the request and response being assigned to the same variable req

To fix this issue, update

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

Answer №2

After taking a look at the server-side code provided, it seems that everything is functioning correctly. To further troubleshoot, you can incorporate console.log statements in the /post route:

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("/");

});

This will allow you to inspect the data being passed and track the changes made to the imagedata array.

Answer №3

It appears that the question is lacking clarity, but perhaps this solution aligns with what you are seeking. However, I fail to perceive the necessity of using a map instead of an object in this context. For more insights on when to utilize a map, refer to this post here

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(express.static("public"));
const 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){
    const NewPost = req.body.url;
    const Description = req.body.description;

    let map = new Map() 
    map.set('url', NewPost).set('description', Description)
    
    imagedata.push(map);
    res.redirect("/");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Running multiple node applications within NGINX subdirectories

My current setup involves a Digital Ocean droplet connected to a domain. NGINX is running on the server, and I am attempting to reverse proxy multiple node apps. At the moment, there is one node express app in the root directory located at / . I'm no ...

The issue of calling the child window function from the parent window upon clicking does not seem to be functioning properly on Safari and Chrome

I'm attempting to invoke the function of a child window from the parent window when a click event occurs. Strangely, this code works in Firefox but not in Safari or Chrome. Here is the code snippet I am using: var iframeElem = document.getElementById( ...

Encountering difficulties while trying to set up the Stripe npm package

I'm encountering a problem while attempting to add the Stripe NPM Package to my React project using npm. The terminal is showing this error message. PS C:\Users\adity\OneDrive\Desktop\stripe-payments> npm i @stripe/react-st ...

How can I use AJAX to transmit a 2D array to a PHP page and then display each dimension individually?

Recently, I created a webpage with multiple checkboxes. Using jQuery, I am able to fetch data from these checkboxes and store them in a two-dimensional array. Here is an excerpt of my code: HTML snippet: <input type="checkbox" name="checkboxs[]" pric ...

When using jQuery each method, it may return an [object Object]

Having an issue with the html variable displaying [object Object] instead of actual elements. Any suggestions on what I should change? var html = ''; $.each(data.response, function(index, value) { var tr = $('<tr>'); var ...

The functionality of the anchor tag is restricted in both Chrome and Safari browsers

I'm having an issue with HTML anchor tags not working properly in Chrome and Safari. Instead of scrolling up, the page scrolls down when clicked. Here is the HTML code I'm using: <a id="to-top"></a> <a class="button toTop" href="# ...

Can JavaScript be used to create a CSRF token and PHP to check its validity?

For my PHP projects, I have implemented a CSRF token generation system where the token is stored in the session and then compared with the $_POST['token'] request. Now, I need to replicate this functionality for GitHub Pages. While I have found a ...

Direction of Agm: Display the panel within a separate component

I have a unique setup where I have divided my page into two components, with one taking up 70% of the space and the other occupying 30%. The first component contains a map while the second one is meant to display information on how to reach a destination ( ...

What is the best way to display an error message when a necessary field is left empty?

I am currently utilizing a plugin to validate my form. My goal is to display an error message on the button when clicked, as all fields in my form are required and need validation. Despite attempting the code below, it hasn't been successful: <Fo ...

leafletjs: render Points of Interest (POIs) using canvas technology

I am looking for a way to efficiently draw multiple geo points using Leaflet and HTML5 canvas. My data source is geoJSON, but according to the documentation of Leaflet, drawing geo positions as canvas is currently not supported. var anotherGeojsonLayer = ...

Encountering an issue in a Vue console where the $ref is returning null and prompting an error message

It's puzzling why I keep encountering a console error in Vue that says "cannot read null of a $ref". Despite having the correct HTML template and adding logic to the script tag as needed, I'm still facing this issue - Cannot read properties of nu ...

Tips for performing an integration test on a material UI <Slider /> component using either userEvent or fireEvent

I'm facing some challenges while trying to perform an integration test on a material UI component. I can locate the slider element, but have not been successful in moving the slider and retrieving the new value. Can you provide any guidance on how to ...

Forward the jsp to the servlet before navigating to the following page

Issue: After submitting the JSP form on Page1, it redirects to a server-side JSP page but appears as a blank page in the browser. Instead, I want it to redirect to Page2 which includes a list box that highlights the newly created item. Seeking help with t ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...

Entering a value into an HTML textbox using Awesomium in VB.NET

This code snippet is used to split text from a listbox: For Each Item As Object In ListBox1.SelectedItems TextBox2.AppendText(Item.ToString + Environment.NewLine) Next Dim str As String = TextBox2.Text D ...

Is there a way to enable Fancybox to change to the adjacent gallery by simply using the 'up' or 'down' arrow keys?

I am currently working on a layout that consists of a vertical column of thumbnail images, each linked to its own gallery with additional images. When the user clicks on a thumbnail image, Fancybox opens, allowing them to navigate through the images within ...

Exploring the World of Unit Testing with Jasmine and Sinon Factories

At my factory, I have implemented a getter and setter function .factory('myService', function() { var car = null; return { car: car, get: function get() { return car; }, set: function set(newCar) { car = newCar; ...

Is it time to execute a mocha test?

Good day, I am currently exploring the world of software testing and recently installed Mocha. However, I seem to be encountering an issue with running a basic test that involves comparing two numbers. Can someone please guide me on why this is happening a ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

Issue in CakePHP after modifying the directory of Index

I'm currently working on a project using CakePHP and have come across an issue. Our team developed an Ajax function that sends data to a PHP function responsible for adding a folder (known as "ordner" in German) to the database. Initially, everything ...