Unable to locate request object during post request

I've created a pug form with the following structure:

extends layout

block content
  h1 David A Hines
  h2 #{posts[0].title}
  p #{posts[0].body}
  div
   form(action='/insert_post',method='post')
    div(id='title_div',data-role='fieldcontain')
      fieldset(data-role='controlgroup')
        p
          label(for='title') Title
        p
          input(id='title',type='text',value='',placeholder='')
      fieldset(data-role='controlgroup')
        p
          label(for='body') Body
        p
          textarea(id='body',cols="40", rows="5", type='textarea',value='',placeholder='')
      fieldset(data-role='controlgroup')
        label(for='author_name') Author Name
        input(id='author_name',type='text',value='',placeholder='')
        label(for='author_email') Author Email
        input(id='author_email',type='text',value='',placeholder='')
    div(data-role='fieldcontain')   
       input(type='submit',value='Submit Post',data-transition='fade', data-theme='c')

When submitting the form to /insert_post, I encounter an issue where the request object is null.

Below is the insert_post action code snippet:

router.post('/insert_post', function(req, res, next) {
    var postsArray = [];
    MongoClient.connect(database.url, function(err, db) {
        var db = db.db(database.database);
        if (!err) {
            console.log("We are connected");
            var postsCollection = db.collection('posts');
            console.log("request: "+JSON.stringify(req.body));
            var postObject = {
              title: req.body.title,
              body: req.body.body,
              author: {
                name: req.body.name,
                email: req.body.email
              }
            }
            postsCollection.insertOne(postObject, function(err, response) {
                console.log("Inserted Post: "+JSON.stringify(response.ops[0]));
                res.render('index', {
                    posts: response.ops[0]
                });
            });
        } else {
            console.log("error:" + err);
            res.end("error: " + err);
        }
    });
});

I have verified that bodyParser is installed in my app.js file, so I am unsure why the request.body is null.

EDIT: My package.json indicates an express version of ~4.16.0, which should not require the use of bodyParser according to its specifications.

Answer №1

Note: Make sure to include the name in the input fields when posting data to Express Node.js.

Server-side Code:-

 router.post('/insert_post', function(req, res, next) {
        var postsArray = [];
        MongoClient.connect(database.url, function(err, db) {
            var db = db.db(database.database);
            if (!err) {
                console.log("Connection established");
                var postsCollection = db.collection('posts');
                console.log("request: "+JSON.stringify(req.body));
                var postObject = {
                  title: req.body.title,
                  body: req.body.body,
                  author: {
                    name: req.body.author_name,
                    email: req.body.author_email
                  }
                }
                postsCollection.insertOne(postObject, function(err, response) {
                    console.log("Inserted Post: "+JSON.stringify(response.ops[0]));
                    res.render('index', {
                        posts: response.ops[0]
                    });
                });
            } else {
                console.log("error:" + err);
                res.end("error: " + err);
            }
        });
    });

Pug file code :-

 extends layout

    block content
      h1 David A Hines
      h2 #{posts[0].title}
      p #{posts[0].body}
      div
       form(action='/insert_post',method='post')
        div(id='title_div',data-role='fieldcontain')
          fieldset(data-role='controlgroup')
            p
              label(for='title') Title
            p
              input(id='title',name='title',type='text',value='',placeholder='')
          fieldset(data-role='controlgroup')
            p
              label(for='body') Body
            p
              textarea(id='body',name='body',cols="40", rows="5", type='textarea',value='',placeholder='')
          fieldset(data-role='controlgroup')
            label(for='author_name') Author Name
            input(id='author_name',name='author_name',type='text',value='',placeholder='')
            label(for='author_email') Author Email
            input(id='author_email',name='author_email',type='text',value='',placeholder='')
        div(data-role='fieldcontain')   
           input(type='submit',value='Submit Post',data-transition='fade', data-theme='c')

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

Tips for aligning a select and select box when the position of the select has been modified

Recently, I encountered an interesting issue with the default html select element. When you click on the select, its position changes, but the box below it fails to adjust its position accordingly. https://i.stack.imgur.com/SwL3Q.gif Below is a basic cod ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

When the Node.js code is executed, it will send back an XML element for any ID parameter

I am having trouble getting the content to load when I type any of the element's ID from the last XML. Currently, the code only returns content if I type in the last element's ID. How can I modify it to load content and page for any of the elemen ...

Encountering challenges with MongoDB's Bulk API as I attempt to transfer my JSON data to MongoDB through NodeJS

Having trouble uploading my json file to MongoDB in a sequential manner using the Bulk API. I keep getting an error message stating "TypeError: bulk.insert is not a function". I've checked the documentation and my syntax seems fine. Any suggestions o ...

What is the best way to store all rows in a dynamically changing table with AngularJS?

I am facing an issue while trying to dynamically add rows for a variable that is a String array in my database. The problem is that it only saves the last value entered in the row instead of saving all of them in an array. Here is my current view code: &l ...

Map failing to refresh

Having some trouble with the map function as it's not updating my select box with the new selected value. The issue occurs within a material UI dialog that appears when viewing a file. I notice that the values get updated only after closing and reopen ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

Can GET or POST variables be transmitted to external JavaScript?

Is it possible to pass a variable to an external JavaScript file? For instance: Suppose I have the following code: <script type="text/javascript" src="gallery.js"></script> I'm curious to know if it's feasible to pass an argument ...

What is the best way to securely store and retrieve API keys within a React application built with Webpack?

Currently developing a project using React, Babel, and Webpack on the front end. Need to find a secure way to store and access API keys for the project. Considering storing API keys in the .env file, which is listed in .gitignore to keep it private. Howe ...

What is the best way to send an array as a parameter to a Vertica query in a node.js environment?

Currently, I am working on executing SQL queries against a Vertica database. This process has been successful so far. However, in order to prevent SQL injection, I have decided to use parameterized queries. It seems that Vertica supports parameters as ? (u ...

Exploring the world of jQuery and Ajax to retrieve a full HTML framework

I'm a beginner in jQuery and JavaScript programming. While I've managed to use jQuery for my Ajax calls, I'm facing an issue that has me stumped. When making an Ajax call, I'm trying to return a complete HTML structure, specifically a ...

Sending an AJAX request to submit a form and receiving a response

I am in the process of developing a Rails application and I am seeking a way to submit a form using Ajax. This functionality is crucial as I want the form submission to occur without causing a full page reload. Initially, I tried using form_remote_tag but ...

Issues have been raised with IE11's refusal to accept string(variable) as a parameter for the localStorage

Why is it that Internet Explorer does not recognize a string variable as a parameter for the setItem method, even though it works fine in Chrome? For example, in IE: This code snippet works: var itemName = 'anyname'; localStorage.setItem(itemN ...

Error: Failed to convert value "NaN" to ObjectId for the "_id" field

[ Issue resolved... the solution turned out to be surprisingly simple... $scope.article = articleFactory.getArticles().get({id:parseInt($stateParams.id,10)}) .$promise.then( should have been: $scope.article = articleFactory.getArticles().get ...

Why am I unable to access all elements within the map function?

Hey there, I have a function related query. Whenever I try to access my data, I can only reach the first index of each array. For instance, I have 5 different images of PlayStation, but on my webpage, I am only able to see one image. How can I resolve this ...

Passing Private Data Between NodesIs it possible for a node to

In my Express route (item/update/), after processing, I intend to redirect the user back to /. Furthermore, I would like to display an alert on / indicating either 'Success' or 'Failure'. To achieve this, without exposing data through q ...

Wait for the canvas to fully load before locating the base64 data in HTML5

Wait until the full canvas is loaded before finding the base64 of that canvas, rather than relying on a fixed time interval. function make_base(bg_img, width, height) { return new Promise(function(resolve, reject) { base_image = new Image(); base_imag ...

Issue: Attempting to access the `userName` property on an undefined object (`tem`), resulting in a TypeError while using flalist

A concern has arisen with the React Native Flatlist as it fails to render properly. What steps should be taken in this scenario? Below is the code snippet for reference: Image description available here import React, {useState, useEffect} from 'react ...

Receiving a response from a Node.js server using an AJAX GET request

Here's a snippet of code from app.js that retrieves an aggregated value from mongo.db. I'm attempting to use this response value on my HTML page by making an AJAX call. However, I'm facing an issue where I can't retrieve the value in my ...

When node.js v6.11.2 is installed on Windows 7, it does not include the correct npm version

When trying to install node.js v6.11.2 on my Windows 7 computer, I am encountering an issue where it is installing the incorrect version of npm alongside it. Even after downloading the installer directly from node.js' website which claims that 6.11.2 ...