Strategies for resolving the issue of undefined req.body.password in express.js

Hello everyone, I am currently in the process of building an API using EXPRESS.JS and MongoDB. While testing with postman, I encountered an issue where the req.body.password field is undefined when attempting to parse it using postman. Strangely enough, I am able to successfully parse the name and email fields, but the password remains undefined. Any assistance would be greatly appreciated!

Below are the files related to this:

userController.js file

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const asyncHandler = require('express-async-handler');
const User = require('../models/userModel');

// Register New User
// POST /api/users
// Public Access
const userRegister = asyncHandler(async (req, res) => {
  const {name, email, password} = req.body;
  res.json({name: `${name}`, email: `${email}`, password: `${password}`});

  if (!name || !email) {
    res.status(400);
    throw new Error('Please Enter valid Inputs');
  }
  res.json({ message: 'User Register' });
});

// Authenticate User
// POST /api/users/login
// Public Access
const userLogin = asyncHandler(async (req, res) => {
  res.json({ message: 'User Login' });
});

// User Data
// POST /api/users/member
// Public Access
const userMember = asyncHandler(async (req, res) => {
  res.json({ message: 'User Member' });
});

module.exports = {
  userRegister,
  userLogin,
  userMember,
};

server.js

const express = require('express');
const colors = require('colors');
const dotenv = require('dotenv').config();
const { errorHandler } = require('./middleware/errorMiddleware');
const connectDB = require('./config/db');
const port = process.env.PORT || 8000;

connectDB();

const app = express();

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

const userRoute = require('./routes/userRoutes');

app.use('/api/users', userRoute);

app.use(errorHandler);

app.listen(port, () => console.log(`Server running on http://localhost:${port}`));

route file

const express = require('express');
const router = express.Router();

const {
  userRegister,
  userLogin,
  userMember,
} = require('../controllers/userController');

router.route('/').post(userRegister);
router.route('/member').post(userMember);
router.route('/login').post(userLogin);
module.exports = router;

userModel.js file

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model('User', userSchema);

POSTMAN Output

https://i.stack.imgur.com/mb8xW.png

Answer №1

By simply making this adjustment, I managed to resolve the issue

const {name, email, password} = req.body;

changed it to

const {name, email, pass} = req.body;

Switching password with pass

This modification did the trick for me

https://i.stack.imgur.com/IgHec.png

Many thanks for your assistance

Blockquote

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

Warning in Next.js: Each element in a list requires a distinct "key" property

Currently, I am in the process of building an e-commerce platform using Nextjs. My current focus is on enhancing the functionality of the myCart page, which serves as a dashboard for displaying the list of items that have been ordered. Below is the code s ...

Utilizing Business Logic in a MEAN Stack Environment

When developing an Angular application, where should the calculations take place - on the front end or back end? Considering that the outputs need to update with each input change, is it practical to send a request to the back end every time there is an ...

Cease the execution of a task in Express.js once the request timeout has been

Suppose we have the following code snippet with a timeout of 5 seconds: router.get('/timeout', async (req, res, next) => { req.setTimeout(5000, () => { res.status(503) res.send() }) while (true) { ...

The image stored in the Images directory of Node.js is not displaying on the website

Having trouble adding an image to my index.ejs file. The code doesn't seem to be pulling the image from the specified /image folder in the second code block. Any tips on how to resolve this issue would be greatly appreciated! const express = require( ...

Exploring the Integration of Callbacks and Promises in Express.js

I'm currently developing an Express.js application where I am utilizing x-ray as a scraping tool to extract information. For each individual website I scrape, I intend to establish a unique model due to the distinct data and procedures involved in th ...

Issue with destructuring in Express.js and React.js that persists

I have a tech stack consisting of ReactJS, ExpressJS, NodeJS, PostgreSQL, and Redux. My current challenge involves fetching a single row from a SQL table on the backend using an axios request. The data is returned within an object inside an array [{..}]. ...

Tips for including a personalized error message in an API response

I am looking to implement proper error handling in my endpoint. For testing purposes, I intentionally introduced a syntax error in the raw JSON body of a request made using Postman. I do not want to receive a response like this: <!DOCTYPE html> < ...

Preventing decimal inputs in Joi validation with node.js

I have included joi validation for certain parameters, but I am now looking to add validation for the "point" parameter to accept decimal values. Below is my current validation code: const userSchema = Joi.object({ point: Joi.number().max(150).required ...

A comprehensive guide to Cassandra error codes

Upon utilizing the datastax node.js driver, an exception code has surfaced as indicated in the documentation at . Yet, I am unable to locate any comprehensive documentation detailing all available exception codes. Does anyone have suggestions on where to ...

Error: You have attempted to execute a command without first establishing a connection, resulting in an Unhandled Promise Rejection warning

While working on integrating selenium-webdriver with nodeJs, everything was going smoothly until I encountered an error in the terminal. What could be causing this issue? UnhandledPromiseRejectionWarning: NoSuchSessionError: Tried to run command without ...

What is the best method for incorporating meta data, titles, and other information at dynamic pages using Node.js and Express?

I am currently exploring methods to efficiently pass data to the html head of my project. I require a custom title, meta description, and other elements for each page within my website. Upon initial thought, one method that comes to mind is passing the da ...

Issue with Express.js and EJS application: The edit form fails to display the current category of the post

I've been developing a blogging application using Express, EJS, and MongoDB. You can check out the GitHub repository by clicking on the link. Within my application, I have separate collections for Posts and Post Categories. One issue I'm encoun ...

Issue encountered while attempting to load bootstrap in NodeJS

I encountered an error while running my jasmine test case in node. The error message says that TypeError: $(...).modal is not a function. This error pertains to a modal dialog, which is essentially a bootstrap component. To address this issue, I attempted ...

Child processes in Node.js are having trouble executing Python code and becoming unresponsive

I have a Node.js application using Express, but I need to execute Python code (send data and receive results). However, when testing it with Postman, it just keeps loading with no response. Here is my Node.js code: router.get('/name', callName) ...

Issue with ElectronJs: HelloWorld application failing to launch

I've recently embarked on creating a simple hello world application with Electron JS, following the steps outlined in the official Electron tutorial. Each step has been meticulously executed as instructed. The process involved the creation of 3 esse ...

Guide: Redirecting to the dashboard in React.js with Redux after a successful login

I have implemented a login page in React JS and an API in Node.js. I am currently working on enabling login functionality using email and password with Redux. Login Page const Login = () => { const [email, setEmail] = useState(""); const [pass ...

Troubleshooting in VS Code with Mocha and hitting a breakpoint that halts at the 'read-only inlined content from source map' file

Yes, yes, I understand. Current VS Code version is 1.25.1 Mocha version: 4.0.1 Mocha running through launch.json: { "name": "mocha", "protocol": "inspector", "type": "node", "request": "launch", "program": "${workspaceRoot}/node_modu ...

The inputs for Node express middleware are unclear and lack definition

I am currently exploring Node.js as a potential replacement for my existing DOT NET API. I have created middleware to enforce basic non-role authorization in my application, but I am encountering compilation problems with the function inputs. Compilation ...

Encountering an issue with npm install when trying to add dependencies from a private Git

In my package.json file, there is an entry for "rtrk": "https://github.com/me/rtrk.git" under the dependencies. Until recently, running npm install or npm update rtrk commands worked fine. However, today, the npm install (update would ...

Error: The function req.next is not defined

Encountering a peculiar error in my Node application, I suspect it is related to one of the middleware functions. Strangely, the error message directs me to a line of code within my user controller where a res.render() function is called. Despite exhausti ...