APIs/Microservices Exercise Tracker Project

Hello, can anyone explain how I should interpret/how I should incorporate some of the given code for this project? Specifically, the glitch templates for the project have sections of code with the comments “not found middleware” and “error handling middleware”. I commented these out and started to just code my solution but now the thought that I should be incorporating this given code is bugging me.

Thanks to any and all response!

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

const cors = require('cors')

const mongoose = require('mongoose')
mongoose.connect(process.env.MLAB_URI || 'mongodb://localhost/exercise-track' )

app.use(cors())

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())


app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});


// Not found middleware
app.use((req, res, next) => {
  return next({status: 404, message: 'not found'})
})

// Error Handling middleware
app.use((err, req, res, next) => {
  let errCode, errMessage

  if (err.errors) {
    // mongoose validation error
    errCode = 400 // bad request
    const keys = Object.keys(err.errors)
    // report the first validation error
    errMessage = err.errors[keys[0]].message
  } else {
    // generic or custom error
    errCode = err.status || 500
    errMessage = err.message || 'Internal Server Error'
  }
  res.status(errCode).type('txt')
    .send(errMessage)
})

const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

Specifically what is confusing you? Is it this?

// Not found middleware
app.use((req, res, next) => {
  return next({status: 404, message: 'not found'})
})

and the function that follows it. It creates an object that gets passed into the next middleware, and if the next middleware sees that code, it knows that something wrong has happened. But my problem is that there is no logic for it. Wouldn’t that just run for every route? Without running it, I think you would want something like:

router.use(function(req, res, next) {
    if (!req.route)
        return next({ status: 404, message: 'not found' })
    next();
});

or even throw an error. But I may be wrong.

Do you need it? If someone types in a bad route, do you want the generic, default message or do you want to handle it in a custom way?

I hope I’m not missing the point of the original post, but if the question is ‘Why incorporate the ‘not found’ middleware and ‘error-handling’ middleware at all?’, then it might help to answer the question, ‘what happens if res.send() in app.get() successfully sends what it’s supposed to send?’

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});


// Not found middleware
app.use((req, res, next) => {
  return next({status: 404, message: 'not found'})
})

If res.send() in app.get() is successful, the response is ended, and the app.use() following the app.get() won’t fire. If the response isn’t ended, the next app.use() in your code will certainly fire, and thus the user will be aware that they may have entered a bad route, for example.

Like I said, I may have missed the point of the original post, and if so, I apologize.

I found the following blog post helpful:
https://derickbailey.com/2016/05/09/in-what-order-does-my-express-js-middleware-execute/

1 Like

It looks like Will has a better understanding/explanation of what it is doing - my quick interpretation was flawed. My last paragraph deals with the why.

1 Like

Thank you very much! Wrapping my mind around the backend stuff is a great challenge and so I’ll apply everything you’ve responded with!

Eeek, backend troubles! This stuff is coming slowly–I really appreciate all your responses!