Whenever attempting to add a new user, I encounter issues with the Post request not functioning properly

When sending a Post request:

  1. I attempt to retrieve the body of the request
  2. Validate the body content using express validator
  3. Capture any errors that may occur
  4. If an error occurs >> reload the create_user page and log the error in the console as follows:
    { location: 'body', param: 'username', msg: 'UserName is required', value: undefined },
  5. Otherwise, create a new user object from the module schema and hash the password using bcrypt
  6. Save the newUser object, if there are no errors, redirect to the login page, or log the error using console.log

app.js file represents the rootFile

    const express = require('express');

const dotenv = require('dotenv');

const app = express(); //main app variable representing the application

const morgan = require('morgan');

const bodyParser = require("body-parser"); //require the body parser         

const path = require('path');

const expressValidator = require('express-validator');

const bcrypt = require('bcryptjs');

app.use(expressValidator())
          
//require the MongoDB file

const connectDB = require('./server/database/connection');

dotenv.config({ path: 'config.env' });

//setting up the port variable
const PORT = process.env.PORT || 8080;

//requiring morgan file 
//for logging requests 
app.use(morgan('tiny'));

// establishing connection to MongoDB 

connectDB();

// displaying >> req.body
app.use(bodyParser.json());
//app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

createUserForm POST REQUEST CALLBACK FUNCTION

exports.createUserForm = (req, res, next) => {
  console.log('Post CREATE CATEGORY /create-user');
  // retrieving the request body
  const username = req.body.username;
  const password = req.body.password;
  const password2 = req.body.password2;
  // validate the body content using express validator
  req.checkBody('username', 'UserName is required').notEmpty();
  req.checkBody('password', 'Password is required').notEmpty();
  req.checkBody('password2', 'UserName is required').equals(req.body.password);
  // capture any errors that may arise 
  let errors = req.validationErrors();
  if (errors) {
    //if there is an error, render the template
    res.render('users/create_user.ejs', {
      errors: errors //pass along the errors
    }, console.log(errors));
  } else {
    let newUser = new userSchema({
      username: username, // first attribute is the NAME in the model, second is the name value tag in the html file
      password: password
    });
    bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(newUser.password, salt, function(err, hash) {
        if (err) {
          //ERROR PAGE
          console.log(err);
        }
        /// Hashing the password
        newUser.password = hash;
        /// saving the user
        newUser.save(function(err) {
          if (err) {
            console.log(err);
            return;
          } else {
            req.flash('success', 'You successfully registered')
            res.redirect('/halalMunchies/login');
          }
        });
      });
    });
  }
};

The form in the ejs file:

<form action="/halalMunchies/create-user" method="post">

  <div class="form-group">
    <label class="control-label" for="username"> Username </label>
    <input id="username" class="form-control" name="username" required autofocus="autofocus" />
  </div>

  <div class="form-group">
    <label class="control-label" for="password"> Password </label> <input id="password" class="form-control" name="password" required autofocus="autofocus" type="password" />
  </div>

  <div class="form-group">
    <label class="control-label" for="password2"> confirm Password </label> <input id="password2" class="form-control" name="password2" required autofocus="autofocus" type="password" />
  </div>

  <div class="form-group">
    <button type="submit" class="btn btn-success">Add User</button>
  </div>
</form>

After submitting, the form page reloads but nothing is saved in the database. It seems to stop at this part...

if (errors) {
  //if there is an error so rerinder the templet
  res.render('users/create_user.ejs', {
    errors: errors //pass along the errors
  }, console.log(errors));

Answer №1

If you're receiving an undefined body response, it's possible that you forgot to include a body-parsing middleware.

To fix this issue, make sure to add the following code snippet in your main file (such as app.js or server.js):

app.use(express.json());

app.use(express.urlencoded({ extended: false }));

By adding these lines, your server will be able to properly parse incoming requests and retrieve all necessary values.

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

The problem with executing a query in mongoose concerning supertest

Currently, I am using a combination of supertest, mocha, and expect for testing purposes within my application. An issue arose in which the document being returned is null with no accompanying error. router.get('/user', function (req, res) { ...

EJS functionality is operational, however, the HTML content is not displaying

I'm currently developing a timer using Express.js and EJS. My goal is to update the HTML dynamically, but I seem to be encountering an issue where nothing gets displayed. Strangely enough, I can see the output in my CLI with console.log. <div id ...

AngularJS consistently retrieves files regardless of the browser configurations

I'm facing an issue with my NodeJS application and AngularJS frontend. When a user requests a file, it is streamed from the node application to the angular frontend. However, the frontend always downloads the file, regardless of browser settings (e.g. ...

Implement socket.io within expressjs routes instead of the bin/www file

Currently, I am utilizing socket.io within my expressJS application. I have established a socket connection in the bin/www file. My goal is to send data to the client side using socket.emit() in the sendmessage.js file when data is sent to it. bin/www ...

Encountered an issue with the property 'push' not being defined

Here's the schema for my mongoose model in JavaScript: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const CartSchema = new Schema({ userID: String, items: [{ itemID: String, quantity: Number }] }); modul ...

A guide on waiting for a streaming SQL query in Node.js

I'm in need of reaching out to a function that executes a SQL query with row-level functionality, and I must await the entire process before proceeding. Function snippet: const sql = require('mssql') exports.doit = ()=>{ const pool ...

Getting the download URL generated by Firebase on a Firebase function is a common task that can

After successfully uploading an image using the Firebase SDK in Flutter, I am able to retrieve the download URL on the Flutter side by calling getDownloadUrl() on the reference. Now, my goal is to access this URL in my Cloud Function trigger so that once a ...

What is the best way to limit the ability to upload a file on Amazon S3 using a presignedUrl to only the

I have successfully implemented the generation of preSignedUrl with an expiration for uploading images. However, I am concerned about the security implications and how to prevent malicious users from abusing this feature. For example, on my Node.js server ...

Some of the CSS code in my file is not displaying properly on my ejs file

For some reason, only the CSS styles for my footer are rendering on my ejs file. The rest of my CSS doesn't render at all. I've tried defining the path of my static files to my views directory using the path method: app.use(express.static(path.jo ...

"Encountered npm error: JSON input ended unexpectedly" while trying to install express-mysql-session"

I'm currently developing a nodejs project that uses passportjs for user authentication and mysql as the database. I'm now looking to incorporate session storage by utilizing the ""express-mysql-session" package. However, when attemptin ...

Having trouble getting Typescript code to function properly when using commonjs style require statements

I am completely new to Typescript, Node.js, and Express. Following the instructions outlined in this tutorial (https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript), I set up my project exactly as described there. The ...

Is it possible to use bearer token authentication when Access-Control-Allow-Credentials is set to false?

My customer authenticates their requests using the header below: Authorization: Bearer some-token If I add this header to my responses, will it cause any issues? Access-Control-Allow-Credentials: false ...

Tips for transferring POST body data to a different route without losing any information

Assuming I have the following route: app.post('/category',function(req,res){ res.redirect('/category/item'); }) In this scenario, the user will submit data to the '/category' route and then automatically be redirected ...

What steps can I take to address this issue with my express node and ejs?

Hey there, I'm new to node.js and I've been encountering this error message. Can someone please provide some insight? Error: Could not find matching close tag for "<%=". at /Users//Desktop/Web Development/getting_started_express js/node_m ...

Mongoose is having trouble connecting, but there are no errors appearing in the console

I am facing an issue with connecting my app.js to MongoDB in a new project. It was working fine previously, but now it won't connect and I don't see any console log or error message. I have double-checked the username and password multiple times. ...

ExpressJs res.json throwing error - Headers cannot be set after they have already been sent

In my current project using ExpressJS, I have a specific route set up like this: router.route('/monitor') .all(function (req, res, next) { next(); }).get(monitor.monitorServers); There is also a controller named 'monitor' which co ...

Tips for executing an SQL query containing a period in its name using JavaScript and Node.JS for an Alexa application

Hello there, I've been attempting to make Alexa announce the outcomes of an SQOL query, but I'm encountering a persistent error whenever I try to incorporate owner.name in the output. this.t("CASEINFO",resp.records[0]._fields.casenumber, resp.r ...

How to Send a Multi-part Message Using AT Commands and PDU Mode in Node.js

I am trying to send a multipart message using AT commands. Single parts work fine, as do special characters. However, when the message exceeds 160 characters, it shows as sent but nothing is received. const async sendSMS(msisdn, message) { message += ...

The local server for handling HTTP requests has ceased to operate

Recently, I set up the NPM package along with the http server within the "server" directory. Initially, everything was functioning smoothly; however, the server abruptly ceased operating. Upon attempting to launch the local http server, an error message a ...

Node.js - The command "which node" yields an incorrect path

I recently decided to reconfigure my node.js settings based on a tutorial that suggested moving the globals folder to a more suitable location. After making these adjustments, I encountered an issue where I was unable to install any packages using NPM. To ...