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:

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

Having trouble getting the "save adjustments" button to become enabled after using the jQuery datepicker

It's puzzling that my code doesn't respond to the selection of a date using the jQuery date picker to re-enable the "save changes" button. Interestingly, changing values in other input boxes seems to work perfectly fine. I'm struggling to gr ...

Watching a service's attribute from within a route in the EmberJS framework

There seems to be a concept that I'm struggling to grasp here. To my understanding, any instance of Ember.object should be able to observe properties on another instance of Ember.object. In my scenario, there is a service, a router, and a component i ...

Transformation of Array of Objects to Array of Values using Node.js

I am looking to transform the following: [{ prop1: '100', prop2: false, prop3: null, prop4: 'abc' }, { prop1: '102', prop2: false, prop3: null, prop4: 'def' } ] into this format: [[100,false,null,'abc&ap ...

reverting the effects of a javascript animation

I am expanding the size of a carousel on a specific pane by adjusting its height and position. Here is how I achieve this: if(currentPane==2) { $("#carousel").animate({height:320},1000); $("#carousel").animate({top:411},1000); $("#dropShadow") ...

Time for the browser to evaluate javascript code has arrived

We are looking to enhance the speed at which our Javascript files load in the browser. Although our own Javascript files are simple and small, larger libraries like jQuery and KendoUI take a considerable amount of time to evaluate. We are interested in fin ...

Adjust the ng-show attribute in a different controller

I am attempting to toggle the visibility of a div using ng-show. Specifically, I have a navbar that should only be displayed in certain views. I have one controller managing the behavior of this div, and another controller where I want to manipulate the v ...

JavaScript is unable to identify one of the JSON values

I am trying to extract the email field from a JSON file using JavaScript. Here is the snippet of code: "contacts": [ { "addedAt": 1332358711001, "vid": 1, "properties": { ...

Encountered an error when attempting to load resource: net::ERR_CERT_AUTHORITY_INVALID following deployment on Vercel

I recently deployed a chatUI-app on Vercel that fetches chats from an API located at "http://3.111.128.67/assignment/chat?page=0" While the app worked perfectly in development, I encountered an issue after deploying it on Vercel where it ...

Retrieving data from an external API using Express.js and displaying it on a website

I'm facing a challenge in handling a solution with node.js and express.js utilizing pug for rendering HTML. I need to render on a single page by retrieving values from separate HTTP GET requests from different websites. My goal is for express/node to ...

Unlimited highway CSS3 motion

I have come across a stunning 2D Highway background image that I plan to use for my mobile racing game project which involves JS and CSS3. The image can be found at this link. My goal is to create an animation of the road in order to give players the illu ...

What is the best method to transform URI data encoded in base64 into a file on the server side?

Looking for a solution to save a URI-data string as a jpg on the server using only Javascript. The alternative of writing it to a canvas and reading the image from there is not ideal. Any ideas? ...

Having trouble adding HTML content to a parent div using jQuery and BackboneJS?

Utilizing Backbone Marionette to create a series of views, I am now faced with the task of making an AJAX call to my backend. In order to provide visual feedback to the user indicating that an action is being performed, I decided to integrate a spinner int ...

What is the maximum number of JavaScript functions allowed in a single HTML file?

My HTML5 file includes JavaScript (created from CoffeeScript) directly within the HTML file, as I prefer this approach for my HTML/JavaScript programming. The code consists of four JavaScript functions that convert one temperature unit to another. Strang ...

Tips for resolving the final item issue in Owl Carousel when using right-to-left (RTL)

Encountering a bug with the rtl setting in owl-carousel. When the rtl is applied to the slider and I reach the last item, the entire slider disappears! Here's the code snippet: var viewportWidth = $("body").innerWidth(); if (viewportWidth & ...

Angular's jQuery timepicker allows users to easily select a

Transitioning from jQuery to Angular, we previously utilized the for selecting times due to Firefox not supporting HTML5 input time. While searching for a similar timepicker plugin for Angular to maintain consistency with our past data and styles, I came ...

Convert HTML table data to JSON format and customize cell values

Hey there, I have a HTML table that looks like this: <table id="people" border="1"> <thead> <tr> <th>Name</th> <th>Places</th> <th>Grade</th> </tr> & ...

How can you implement a resource response approach in Express.js using an API?

As a newcomer in my journey with expressjs, I'm currently exploring its functionalities. In my controller, I've structured the response as follows: .... res.json({ 'data': { 'user': { 'id': us ...

Storing JSON data in Sequelize

I am faced with the task of saving a json object sent by a client into a database. Although the application can handle requests successfully, I am encountering difficulties in storing the request data in the database, using sequelize. Here are my models: ...

Struggling to get the ReactJS.NET MVC tutorial to function properly?

After deciding to start a new project in Visual Studio with MVC 5 and a single page app using ReactJS, I consulted the guide on the ReactJS website. Upon running the project for the first time, I encountered a syntax error due to JSX. It seemed that the b ...

Javascript: triggering a self-executing function manually

I have a code snippet similar to the following: var msg="first call"; (function test(msg) { console.log("inside self call"); } )(); msg="second call"; console.log("before inline call"); test(msg); console.log("after inline call"); In thi ...