Unable to access request body data from API - value not defined

It's been a couple of hours and I'm still stuck on this issue >.<

I'm having trouble accessing the request body for the user API. While I can retrieve the response 'hi' using res.send (as shown in the screenshot), I'm not able to capture any req.body values. The email is returning as undefined :/

Any thoughts on where I might be making a mistake?

The content type is set to JSON in the Postman headers.

Controller:

import asyncHandler from 'express-async-handler'

const authUser = asyncHandler(async (req, res) => {
    const { email, password } = req.body
  
    res.send('hi' + email)
    
})

export {authUser}

Route:

import express from 'express'
const router = express.Router()
import { authUser } from '../controllers/userController.js'

router.post('/login', authUser)

export default router

https://i.sstatic.net/ooBJl.png

hiundefined ^

Server.js

import express from 'express'
import dotenv from 'dotenv'
import connectDB from './config/db.js'
import productRoutes from './routes/productRoutes.js'
import userRoutes from './routes/userRoutes.js'
import colours from 'colours'
import { notFound, errorHandler} from './middleware/errorMiddleware.js'

dotenv.config()

connectDB()

const app = express()

app.use(express.json())

app.get('/', (req, res) => {
    res.send('API is running...')
})

app.use('/api/products/', productRoutes)
app.use('/api/users/', userRoutes)

app.use(notFound)
app.use(errorHandler)

const PORT = process.env.PORT || 5000

app.listen(
    PORT,
    console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold)
)

Headers: https://i.sstatic.net/pVUaZ.png

Answer №1

For those using Express 4.16+, it is recommended to utilize this middleware: app.use(express.json())

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyparser.json());

Additionally, remember to update your header request accept with Content-Length:

<calculated when request is sent>
`` https://i.sstatic.net/qRAbY.png

Answer №2

I suggest that you ensure the request req is passed to your authUser function in order for it to work properly

router.post('/login', (req, res) => {
  authUser(req, res)
});

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 could be causing the jQuery blur function to malfunction in the tag-it library?

My attempts to implement JQuery's blur with the tag-it library have been unsuccessful. I cannot figure out why the blur function is not functioning properly. When clicking off the input field, nothing happens and there are no error messages. The al ...

Is there a way to nest arrays within arrays in JavaScript?

Array ( [0] => Array ( [contactId] => 5 [companyId] => 54 [personName] => Awais [contactNo] => 0321-1111111 [contactType] => Partner ) ) data[0].personName I ...

Javascript puzzle - I have 99 obstacles

...but a malfunction isn't one. Hey there, I am new to learning so I apologize for the seemingly simple question. I'm experimenting with a theoretical logic statement that would work using javascript. For instance: if (issues == 99) { malfunct ...

Troubleshooting your Meteor App on Nitrous.io with server-side debugging

I currently have a basic Meteor application up and running on a Nitrous box. I am interested in utilizing node-inspector for debugging the server-side part of my app, but I'm facing difficulty accessing the console as detailed here. The Meteor app is ...

Having trouble utilizing the $ selector within a for loop? Avoid attempting to use $("$i") and try an alternative method instead

for (var i = 0; i < 9; i++) { a[i] = val($("#" + i)); alert(a[i]); } UPDATE: The previous code was incorrect as it selected elements with id(#) 'i', which is invalid. Therefore, "#" + i should be used instead. My query was: How c ...

React Component: Issue with conditional "if else" statement not refreshing in return statement

Starting out in React and the front-end field with minimal experience. Currently attempting to dynamically change the color of the "fill" property in a polygon element using React. If the percentage is greater than 50, I want the color to be green; otherw ...

How can we use res.render to refresh page routes?

(Working with MEAN Stack and UI Router) In the code snippet below, a json response is sent for the specified route. While this setup functions properly when the template is rendered using UI Router, an issue arises upon page reload. Due to the response co ...

What is the process for converting several files into a base64 string?

I have a component set up like this: <input type="file" multiple @change="toBase64Handler($event)"> <script> data() { return { files: [], } }, methods: { tobase64Handler(event) { // implementation } } </script> I w ...

Listening to audio on a mobile browser using an HTML audio element

What is the solution for the problem of playing audio on a mobile browser when it plays on a desktop browser but not on mobile? The code being used is: var audio = new Audio('sound.mp4') audio.play() ...

Fetching information from server proves to be sluggish within AngularJS application

In the process of developing a web application, I am faced with the task of sending numerous $http requests to the server. My front-end is built using AngularJS while the back-end utilizes ExpressJS. The $http requests are currently being made as shown in ...

The MongoDB Node cursor could not be located due to a false timeout setting

In my nodejs/express server, I am attempting to merge and sort sorted results from multiple mongodb collections to create a sorted CSV file. My method involves keeping the mongodb cursors alive (without timing out) until all data is read or an error occurs ...

Variables for NPM Configuration

After researching the best way to securely store sensitive information, I decided to utilize the config package and environment variables for added security. Here is how I implemented this setup: Created a config directory containing two files: default.js ...

Is it possible to incorporate an additional value into the jQuery widget 'Autocomplete' by using a second variable?

For several years, I have been utilizing the jQuery 'Autocomplete Widget' in my projects. This plugin allows me to pass a value labeled as 'term' to the PHP SQL code that works like this: $( "#cs1" ).autocomplete({ aut ...

Rendering EJS templates and smoothly scrolling to a specific section on a webpage

I need to display my index page and automatically scroll down to the form section. One way I thought of doing this is by: app.post('/rsvp', (req, res) => { res.render('index/#rsvp', { errors: { email: 'Your email has already ...

The ObjectSpaceNormalMap feature is not functioning properly when used in conjunction with MeshNormal

I'm having trouble getting the MeshNormalMaterial to stay aligned with the object instead of the camera. I set .normalMapType = THREE.ObjectSpaceNormalMap, but it doesn't seem to be working as expected. Is there something crucial that I might b ...

Tips for Making JQuery UI Droppable Work with Multiple Elements

I've been tasked with modifying a piece of code that currently allows users to drag one row from a table to a div. The new requirement is to enable users to select multiple rows and drag them all to the div. I'm struggling to tweak the existing c ...

Troubleshooting a Dysfunctioning Character Counter Feature in a JavaScript Input Field

I've been working on a fun little project to practice my JavaScript skills - a plate calculator. Here's the gist: you enter your name, and each letter costs $5, so the total cost of the plate is the length of your name multiplied by $5 (this pro ...

Javascript error: The variable calculator_test has not been defined

Why am I receiving an error message: Uncaught ReferenceError: calculator_test is not defined index.html: <!DOCTYPE html> <html> <body> <p>Click the button</p> <button onclick="calculator_test()">test</button> &l ...

Direct express towards React's landing page

As a newcomer to React and Node, I have organized my project into two folders: Client, running on port 3000 Server, using Express on port 3001 Although registration process is working fine, I am facing an issue with the authentication process. Currently ...

What is the best way to confirm only one click per browser?

Is there a way to limit rating functionality to allow users to rate only once per browser session? I am looking to implement validation for a rating component in React where users can only submit their rating once per browser. Below is an example of the ...