The error middleware in Express is not defined

I'm facing an issue where the Express API error messages are returning as undefined on the frontend. This is preventing me from displaying proper error messages to alert users.

Interestingly, the error messages seem to appear fine in the developer tools.

My setup involves using Express, Redux, and authentication middleware.

I have been trying to debug this problem but can't seem to figure out where I might have made a mistake. Any insights into why the error messages are undefined?

Error message component (error is undefined so it won't show up)

{error && <Message variant='danger'>{error}</Message>}

errorMiddleware.js

const notFound = (req, res, next) => {
    const error = new Error(`Not Found - ${req.originalUrl}`)
    res.status(404)
    next(error)
}

const errorHandler = (err, req, res, next) => {
    const statusCode = res.statusCode === 200 ? 500 : res.statusCode
    res.status(statusCode)
    res.json({
        message: err.message,
        stack: process.env.NODE_ENV === 'production' ? null : err.stack
    })
}

export { notFound, errorHandler }

Correct error message in dev tools:

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

Which matches the login API here:

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

  const user = await User.findOne({ email })

  if (user && (await user.matchPassword(password))) {
    res.json({
      _id: user._id,
      name: user.name,
      email: user.email,
      isAdmin: user.isAdmin,
      token: generateToken(user._id),
    })
  } else {
    res.status(401)
    throw new Error('Invalid email or password')
  }
})

User log in action:

export const login = (email, password) => async(dispatch) => {
    try {
        dispatch({
            type: USER_LOGIN_REQUEST
        })
        const config = {
            headers: {
                headers: {
                    'Content-Type': 'application/json'
                }
            }
        }
        const { data } = await axios.post('/api/users/login', { email, password }, config)
        dispatch({
            type: USER_LOGIN_SUCCESS,
            payload: data
        })
        localStorage.setItem('userInfo', JSON.stringify(data))
    } catch (error) {
        dispatch({
            type: USER_LOGIN_FAIL,
            payload:
              error.response && error.response.data.message
                ? error.response.data.message
                : error.message,
          })
    }
} 

server.js

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

User reducer

import { USER_LOGIN_FAIL, USER_LOGIN_SUCCESS, USER_LOGOUT, USER_LOGIN_REQUEST } from '../constants/userConstants'

export const userLoginReducer = (state = { }, action) => {
    switch(action.type) {
        case USER_LOGIN_REQUEST:
            return { loading: true }
        case USER_LOGIN_SUCCESS:
            return { loading: false, userInfo: action.payload }
        case USER_LOGIN_FAIL:
            return { loading: false, error: action.payLoad }
        case USER_LOGOUT:
            return { }
        default:
            return state
    }
}

userRoutes.js

import express from 'express'
const router = express.Router()
import { authUser, getUserProfile, registerUser } from '../controllers/userController.js'
import { protect } from '../middleware/authMiddleware.js'

router.route('/').post(registerUser)
router.post('/login', authUser)
router.route('/profile').get(protect, getUserProfile)

export default router

Answer №1

Do you happen to be utilizing react and the react context hook? If so, it is likely that you will need to implement a reducer in order to update the error value using action.payload for the scenario when a USER LOGIN FAIL occurs.

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

MaxFieldSize limit exceeded in Node.js

Currently, I am facing an issue while uploading a collection of images to my node.js express server. The error message that I am encountering is "Error: maxFieldsSize exceeded". It seems like the default maximum size for fields (maxFieldsSize) is set to 2M ...

Tips for populating a Flat List with nested JSON data in React-Native

As a beginner in React-Native and Javascript, I'm trying to figure out how to retrieve data for my FlatList. The JSON format I receive is structured like this: [ { "18": { "sellingUnitName": "unité(s)", "qualifier": "GOOD", " ...

Extract data from the Ajax database and automatically hide the "Load More" button when all items

Every time I fetch data from my MySQL database, I retrieve 5 items at once. $query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5"); $query->execute([$_POST["id"]]); while($row = $query -> fetch() ...

Determine the number of working days prior to a specified date in a business setting

How can I calculate X business days before a given date in JavaScript when I have an array of holidays to consider? I am currently thinking about using a while loop to iterate through the dates and checking if it is a business day by comparing it with the ...

Display resize grip when hovering

Is there a way to make elements resizable using resize: both, but only show the corner handle when hovering over the element? I am looking for a solution to display that specific handle only on hover. ...

How can I display API data in a Bootstrap Modal popup window?

The challenge I am facing involves displaying data in a Bootstrap 4 Modal Popup but encountering errors. To tackle this issue, I created a new include file and placed all Modal code inside it. Additionally, I made an axios get request to obtain the API UR ...

Copy the style of a chosen element and apply it to another element

One of the challenges I'm facing involves a dynamic span element that changes based on color selection: <span class="color checked" style="background-color: #ff0000">Red</span> In addition, I have an image element wit ...

Toggle visibility of an Angular 4 component based on the current route

Hello there, I'm facing an issue and not sure if it's possible to resolve. Essentially, I am looking to display a component only when the route matches a certain condition, and hide another component when the route matches a different condition. ...

Utilizing JavaScript or jQuery in MVC4 to showcase information for the primary record

I'm currently working on constructing a page that displays a list of users. My aim is to have a "Details" link in each row that, when clicked, will render a partial view on the same page without having to reload it using either javascript or jQuery. D ...

Using Node.js to display the outcome of an SQL query

I have been attempting to execute a select query from the database and display the results. However, although I can see the result in the console, it does not appear on the index page as expected. Additionally, there seems to be an issue with the way the r ...

Adjust the class of a div element located close to its ancestor using JavaScript

I'm trying to change the class of the element #sidePanel from .compact to .expanded dynamically in this code snippet: <div id="sidePanel" class="compact"></div> <div id="topbar"> <div id="buttonContainer"> <div ...

It appears that the setUser function is not being properly initialized when fetching data from the database

After making a request to fetch a user by ID, I noticed that the data is successfully retrieved from the database as it gets logged in the console. However, for some reason, the state variables are not updating at all. It seems like there might be a small, ...

The Node.js Express application is displaying strange symbols for Hindi characters when querying data from a SQLite database

An API has been developed with Nodejs Express. The Hindi API is currently live and displaying strange characters for the Hindi language, while the English version works perfectly. Below is the code snippet for the Hindi API: app.get("/api/find/hindi/:find ...

Leveraging keyboard input for authentication in Angular

Would it be possible to modify a button so that instead of just clicking on it, users could also enter a secret passphrase on the keyboard to navigate to the next page in Angular? For example, typing "nextpage" would take them to the next page. If you&apo ...

I am looking to modify the background color of characters in a text box once the characters in a textarea exceed 150 characters

Currently, I am utilizing event.data to capture the text inputted into this particular HTML textbox. My intention is to change the background color to red based on that input. However, when using the style attribute on event.data, I encounter an error. It& ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...

refresh the localstorage array using vanilla JavaScript

I am attempting to remove an element from an array stored in local storage. I am using vanilla JavaScript within a Vue.js 3 component. Here is my array: ["96", "281", "287", "415", "650", "661", & ...

Issue encountered in Vuejs when attempting to remove a component using directives while the mounted or created event is still being executed

I created a custom directive that functions like v-if. In the directive, I check access rights and remove the element if access is not granted. Below is my code: Vue.directive('access', { inserted: function(el, binding, vnode){ // ...

AngularJS: Utilizing bold text to enhance the separation of concerns between controllers and templates

In my AngularJS version 1 application with Ecmascript 6, I have a requirement to display a string where one part is in normal weight and the other part is bold. For instance, consider the following scenarios: Will start now Will start in 6 minutes Will ...

What is the best way to transfer a JSX element from a child component to its parent component?

Is it acceptable to send the JSX element from a parent component to a child component through props? From my understanding, using `useState` to store JSX elements is not recommended. Therefore, I can't just pass a callback down to the child and then ...