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

What is the correct way to store user input in the "store" using vuex.js? Can you help me identify where I went wrong?

On the third day of my suffering, I seek your help. Can you please guide me on how to save text input in "store" in vuex.js and then add it to the value of the same input itself? I've attempted it like this but seem to be making a mistake somewhere. ...

Should we pass <script> tags or unsanitized values to the Handlebars layout?

How can I pass values to handlebars that are not sanitized upon output? For instance, I want to ensure that when using the code res.render('index', {script: '<script src="bundle.js"></script>'}), it is not rendered as {{scri ...

What is the best way to change a JavaScript variable into a PHP variable?

I am interested in converting my JavaScript variable to a PHP variable... Currently, I have the following scenario - in the code below there is a variable e, but I would like to utilize e in PHP as $e: <script> function test() { var e = documen ...

Create a new JSON file to preserve the value of a JSON object

I am working with a JSON file that looks like this: { "soils": [{ "mukey": "658854", "mukeyName": "Meggett-Kenansville-Garcon-Eunola-Blanton-Bigbee (s1517)", "sl_source": "Fl soil map", "cokey": "3035468", "soilName": "Eunola", " ...

PHP: Best practices for printing classes and IDs for jQuery rendering

Hey there, I have a question that may sound basic to some, but I need help with echoing this piece of code: echo 'jQuery(document.body).prepend("<div id="notice" class="alert alert-success">Advanced Custom Fields plugin is currently active. & ...

Reveal the concealed button with a jQuery click event

I have a simple question that has been elusive to find an answer for on the internet. Can anyone please help? <input hidden="true" class="btnsubmit" id="myaddslide2" onClick="UPCURSLIDE()" type="button" value="UPDATE"> <script> function ...

`Why setRequestHeader is essential for Ajax and XMLHttpRequest`

Should I ever manually specify the setRequestHeader as 'application/x-www-form-urlencoded' for an ajax POST request? Is it necessary to manually define the setRequestHeader as 'multipart/form-data' when uploading files via ajax? Do XMLH ...

What is the best way to change a byte array into an image using JavaScript?

I need assistance converting a byte array to an image using Javascript for frontend display. I have saved an image into a MySQL database as a blob, and it was first converted to a byte array before storage. When retrieving all table values using a JSON ar ...

Displaying components in Vue 2 using data from an ajax call

How can components retrieved from an ajax response be rendered? For instance, suppose I have registered a component called "Test" and within the ajax response I encounter: <p>dummy paragraph</p> <test></test> <!-- vue component ...

How to add multiple entries using Node.js and Tedious

I am currently working with an array of customer objects that I need to insert into a SQL database. These customer objects are retrieved from the request data. For this task, I am utilizing Tedious for handling the request and Tedious Connectionpool to ma ...

Form submission requires a checkbox to be checked

I have been searching for a way to make checkboxes required. Is there a method similar to using required="required"? Currently, I generate my checkboxes in the following manner and would really appreciate any guidance on this topic. It's crucial for m ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

Remove duplicate JSON records in JavaScript by comparing and filtering based on identical attributes

Looking to remove duplicates from a JSON object [{id:1,name:a, cat:1},{id:1, name:a, cat:2},{id:2, name:b, cat:8}] I want to keep only the first occurrence of each duplicated id [{id:1,name:a, cat:1},{id:2, name:b, cat:8}] ...

"Utilizing d3 to parse and track variables within JSON data

To calculate the number of occurrences of s1, s2, and s0 in JSON data and use this information to plot a multiline chart with date (path of date is as follows reviews_details>>variable vf of JSON) on the X-axis versus the number of reviews (s1/s0/s2 counts ...

The selected attribute does not function properly with the <option> tag in Angular

Currently, I am faced with a challenge involving dropdowns and select2. My task is to edit a product, which includes selecting a category that corresponds to the product. However, when I open the modal, the selected group/category is not displayed in the d ...

ScriptManager is not accessible in the current ASP.Net Core Razor Page context

I'm facing an issue where I have a view (such as Index.cshtml) and a page model (like Index.cshtml.cs). In the view, there's a JavaScript function that I want to call from the OnPost() method in the page model. I tried using ScriptManager for thi ...

Tips on invoking a mixin within a Jade template showcased in a Node/Express endpoint

I'm currently developing a component that I plan to use multiple times on a website through a Jade template. This is how my route is set up: router.get('/', function(req, res, next) { res.render('indicators',{category:"", num ...

objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of ...

An issue with asynchronous execution in Protractor

I have been using and learning protractor for over a month now. Despite the documentation stating that Protractor waits for Angular calls to complete (http://www.protractortest.org/#/), ensuring all steps are executed synchronously, I have not found it ...

What is the process for generating an HTTP response that results in a pipe error being thrown

In my NestJS application, I have created a custom pipe that validates if a given value is a valid URL. If the URL is invalid, an error is thrown. This pipe is utilized in a controller to save an item into the database. Recently, I discovered that the pipe ...