title: Got an error in Express, cant send request
body: <p>controllers/userController.js</p>
  <pre><code>import User from '../models/userModel.js'
  import asyncHandler from 'express-async-handler'
  import generateToken from '../utils/generateToken.js'
  
  // @desc    Auth user &amp; get token
  // @route   POST /api/users/login
  // @access  Public
  const authUser = asyncHandler(async(req, res) =&gt; {
    const { email, password } = req.body
  
    const user = await User.findOne({ email })
    if(user &amp;&amp; (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')
    }
  })
  
  // @desc    Get user Profile
  // @route   GET /api/users/login
  // @access  Private
  const getUserProfile = asyncHandler(async(req, res) =&gt; {
    // res.json(req.user)
    const user = await User.findById(req.user._id)
    console.log('user', user)
    if (user) {
      res.json(user)
    } else {
      res.status(404)
      throw new Error('User not Found')
    }
  })
  
  export { authUser, getUserProfile }
  </code></pre>
  <p>middleware/errorMiddleWare.js</p>
  <pre><code>const notFound = (req, res, next) =&gt; {
    const error = new Error(`Not Found - ${req.originalUrl}`)
    res.status(404)
    next(error)
  }
  
  const errorHandler = (err, req, res, next) =&gt; {
    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 }
  </code></pre>
  <p>middleware/authMiddleware.js</p>
  <pre><code>import jwt from 'jsonwebtoken'
  import asyncHandler from 'express-async-handler'
  import User from '../models/userModel.js'
  
  const protect = asyncHandler(async(req, res, next) =&gt; {
    let token
    if(req.headers.authorization &amp;&amp; req.headers.authorization.startsWith('Bearer')) {
      try {
        token = req.headers.authorization.split(' ')[1]
        const decoded = await jwt.verify(token, process.env.JWT_SECRET)
        req.user = await User.findById(decoded.id).select('-password')
        next()
      } catch (error) {
        res.status(401)
        throw new Error('Not Authorized, token failed')
      }
    }
  
    if(!token) {
      res.status(401)
      throw new Error('Not Authorized')
    }
    next()
  })
  export { protect }
  </code></pre>
  <p>routes/userRoutes.js</p>
  <pre><code>import express from 'express'
  const router = express.Router()
  import { authUser, getUserProfile } from '../controllers/userController.js'
  import { protect } from '../middleware/authMiddleware.js'
  
  router.post('/login', authUser)
  router.route('/profile').get(protect, getUserProfile)
  
  export default router
  </code></pre>
  <p>I got an error in userController.js, error from my errorMiddleware.
  Scenario :</p>
  <ol>
  <li><p>If I send a response from &quot;if statement&quot;. (after User.findById)
  <a href="https://i.stack.imgur.com/NyUF3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NyUF3.png" alt="enter image description here" /></a></p>
  </li>
  <li><p>But if I send response before &quot;if statement&quot;, it work (is not Good). But why? and how can I solve this (to send a response after using User.findById) ?</p>
  </li>
  <li><p>I got an Error in server console when I used scenario 1 or 2.
  <a href="https://i.stack.imgur.com/E1D2U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E1D2U.png" alt="enter image description here" /></a></p>
  </li>
  </ol>
  <p>version
  node 14.12.0
  express 4.17.1</p>