How come my show and edit routes are not recognizing req.body as defined, unlike my create route?

I recently refactored my code to make it more organized by moving some parts into separate models in my app.js file. However, after doing so, I started encountering errors stating that the items within the req.body object are undefined. Unfortunately, I've been unable to pinpoint the cause of this issue despite extensive Google searches, Stackoverflow consultations, and numerous code reviews.

var express = require('express'),
    app = express(), 
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    expressSanitizer = require("express-sanitizer"),
    mongoose = require('mongoose'),
    Job = require("./models/job"),
    Worker = require("./models/worker"),
    Boss = require("./models/boss");

mongoose.connect("mongodb://localhost/tiny_gig", { useNewUrlParser: true });
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(expressSanitizer());
app.use(methodOverride("_method"));

// CREATE ROUTE
app.post("/jobs", function(req,res){
   req.body.job.jobInfo = req.sanitize(req.body.job.jobInfo); // <--- This works just fine.
   // Create job
   Job.create(req.body.job, function(err, newlyCreated){
        if(err){
          res.render("new");
        } else {
          res.redirect("/jobs");
        }       
   });
});

// SHOW ROUTE
app.get("/jobs/:id", function(req, res) {
   // Find the job with the specific ID
   console.log(req.body);
   Job.findById(req.params.id, function(err, foundJob){
      if(err){
        res.redirect("/jobs");
      } else {
        res.render("show", {job: foundJob});
      }
   });
});

// EDIT ROUTE
app.get("/jobs/:id/edit", function(req, res) {
    req.body.job.jobInfo = req.sanitize(req.body.job.jobInfo); // <--- If I comment this line out, everything works...
    Job.findById(req.params.id, function(err, foundJob){
        if(err){
            res.redirect("/jobs");
        } else {
            res.render("edit", {job: foundJob});
        }
    });
});

Check out the EJS templates used:

// EDIT TEMPLATE
<% include partials/header %>
<div class="ui main text container segment">
    <div class="ui huge header">Edit "<%= job.title %>" </div>
    <form class="ui form" action="/jobs/<%= job._id %>?_method=PUT" method="POST"> 
        <div class="field">
            <input type="text" name="job[title]" value="<%= job.title %>">
        </div>
        <div class="field">
            <input type="text" name="job[preview]" value="<%= job.preview %>">
        </div>
        <div class="field">
            <textarea required name="job[jobInfo]"><%= job.jobInfo %></textarea>
        </div>
        <div class="field">
            <input class="ui teal basic button" type="submit">
        </div>
    </form>
</div>
// SHOW TEMPLATE
<% include partials/header %>

<div class="ui main text container ">
    <div class="ui huge header"><%= job.title %></div>

    <div class="ui top attached segment">
        <div class="item">
            <div class="description">
                <p><%=job.jobInfo%></p>
                <div class="content">
                    <span><small>Created on:  <em><%= job.created.toDateString() %></em></small></span>
                </div>
                <a class="ui teal basic button" href="/jobs/<%= job._id %>/edit">Edit</a>
                <form id="delete" action="/jobs/<%= job._id %>?_method=DELETE" method="POST">
                    <button class="ui red basic button">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>
\\ JOBS MODEL
`code`
var mongoose = require("mongoose");

// JOB SCHEMA SETUP
var jobSchema = new mongoose.Schema({
    title: String, 
    preview: String,
    jobInfo: String,
    created: {type: Date, default: Date.now}
});

module.exports = mongoose.model("Job", jobSchema);

The current error message displayed is:

TypeError: Cannot read property 'jobInfo' of undefined
    at /home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/app.js:71:53
    at Layer.handle [as handle_request] (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/layer.js:95:5)
    at /home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:281:22
    at param (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:354:14)
    at param (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:365:14)
    at Function.process_params (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:410:3)
    at next (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:275:10)
    at methodOverride (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/method-override/index.js:65:14)
    at Layer.handle [as handle_request] (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:317:13)
    at /home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:335:12)
    at next (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:275:10)

Answer №1

req.body is only accessible for post requests and not get requests.

The view and edit URLs you have registered are set as get requests. To access URL parameters, you can use req.query.

app.get("/jobs/:id", function(req, res) {

app.get("/jobs/:id/edit", function(req, res) {

The above lines must be adjusted.

Either utilize app.post() or switch from req.body to req.query in order to access URL parameters.

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

Switching between light and dark themes in a Next.js application with Ant Design v5 theme toggle

In my Next.js application using Ant Design v5, I am working on implementing a dynamic theme toggle to switch between light and dark modes. The issue I'm facing is that the initial theme settings work correctly, but subsequent changes to the isDarkMode ...

Encountered a server error while trying to export from Content

I'm attempting to retrieve data from a specific space in Contentful by utilizing the https://github.com/contentful/contentful-export npm package. However, when I execute my code following the example provided on the GitHub page, I encounter the follow ...

Transform a Javascript string variable into plain text within a pre-existing text document

Currently, I am storing user input from an HTML input as a JavaScript variable. The objective is to convert this data into plain text and save it in an existing text file. Essentially, each time the user provides input, it should be converted to plaintext ...

Calculate the total of all values associated with a dynamically generated key within an array of objects

I'm trying to calculate the sum of similar keys in an array of objects. Each object in the array will have some common keys, but not all arrays will share the same set of keys. I'm considering storing these keys in a separate array and then loopi ...

Only users who are logged in to Node.js can access the message

Whenever users are online and do not close our clients like a browser tab or android application, I have the ability to send a message to each specific user by utilizing the following code: socket.broadcast.to(socketId) .emit('new message', ...

Change ES6 JavaScript to ES5 standard

Is there a way to transform this code snippet from other questions into ES5 format? I am attempting to extract data from a JSON array. var match = function(query, input) { return input.filter(function(entry) { return Object.entries(query).every(fun ...

Acquire the Information from a Textarea That Has Been Edited by the User

My challenge lies in taking user-entered text from a content editable textarea and sending it via POST request, but the fields edited by the user are returning with an empty textContent. The code snippet below shows that each .entryRow (obj) contains multi ...

What is the best location to configure Cache-Control when utilizing Firebase Hosting in conjunction with a Cloud Run express server?

With Firebase Hosting + Cloud Run (express server), Firebase Hosting acts as a proxy between your client and server. Where is the best place to define my Cache-Control header? In the firebase.json configuration for Firebase Hosting Or should I set res.se ...

Communication between child and parent components in Vue.js is an essential feature

Attempting to invoke functions from my component to Vue for the login process. This is the code snippet of my component : Vue.component('auths', { data: function() { return { ip: '', sessiontoken: '' } ...

What is causing the qtip tooltip to show up on buttons with different ids?

I have a requirement to display tooltips only for specific buttons and not for others. I am facing an issue where the tooltip intended for the TAB button is showing up when hovering over other buttons like FOO and BAR as well. Could this be due to them sha ...

Changing the 'null' string to null in JavaScript

Within an array of objects, some keys have a value of "null" as a string that I want to convert to null. Here is the code I tried: let obj = [{ "fundcode": "DE", "fundname": "Defens", ...

Use the `fetch` method in JavaScript/TypeScript to make an API call to an IPFS URI but be prepared for potential issues like CORS restrictions, network errors, or

I am currently working on a Next.js project with TypeScript in the browser, and I need to execute the following fetch request: const tokenURIResponse = await fetch( "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg ...

What is the best way to transfer data between functions?

I'm working on a fun Santa's game to play with my friends. The concept is simple: you enter your name, click a button, and a random name from the list will be displayed as the result. I've encountered a couple of challenges: I can succe ...

What is the most effective way to obtain a customer's latitude and location by prompting them to drop a pin on Google Maps?

My Android app has an API, but on my website I'm wondering how I can retrieve a person's location by having them place a marker on a Google Map. Is there a standard method for this? I need to obtain the latitude and longitude coordinates and send ...

Hey there, I am interested in deploying a Node webpack bundled application to Heroku

When working with webpack, I noticed that it always bundles the same way on a local environment. I'm not sure if this is normal or not. Here's a snippet of my Heroku log: -----> Node.js app detected -----> Creating runtime environment ...

Next.js Error: Unable to access the 'collection' property, as it is undefined

I have recently started using next.js and I am interested in creating a Facebook clone by following YouTube tutorials. However, I keep encountering the error message "Cannot read properties of undefined (reading 'collection')". To troubleshoot, I ...

Vue app hosted on Firebase displays a blank page when user logs in

After deploying my Vue2 project to Firebase hosting server, visitors are required to log in to access the other pages. The issue is that once a user successfully logs in, they are redirected to the next page but it appears blank. Below is what the firebas ...

Lately, I've been coming across mentions of "myApp.controllers" and "myApp.modules" in Angular JS. Can anyone explain the significance of these terms?

Recently, I've come across code that looks like this: angular.module('app.controllers') This pattern has appeared in a few tutorials I've read. However, the purpose of the .controllers within the module name is unclear to me. I'v ...

Issues with JQuery script causing inconsistency in checking checkboxes

My code includes two functions designed to check and uncheck all checkboxes with a specific class. Initially, the functions work as expected but upon subsequent attempts to run them, the checkboxes do not function properly. Instead, the HTML code seems to ...

What is the best way to switch focus to the next input using jQuery?

Currently, I am implementing the autocomplete feature using jQuery and everything seems to be functioning properly. The only issue I've encountered is with Internet Explorer (IE) - when a user selects an item from the autocomplete list, the focus does ...