Issue Tracker 404 Middleware Issue

In the following code, I couldn’t get any of the routes to work unless I moved the 404 middleware from server.js to inside the MongoDB connect function in api.js. Is there a better way to handle this?

'use strict';

const MongoClient = require('mongodb');
const ObjectId = require('mongodb').ObjectID;

module.exports = app => {
  MongoClient.connect(process.env.DB, (err, db) => {
    console.log("connection established");
    if(err) {
      console.log(err);
    } else {
      app.route('/api/issues/:project')
        .get((req, res) => {
          console.log(req.params.project);
        })
        .post((req, res) => {
          console.log(req.params.project);
        })
        .put((req, res) => {
          console.log(req.params.project);
        })
        .delete((req, res) => {
          console.log(req.params.project);
        });
    }
  });
};

The 404 route must be the last one to be checked. If you share your glitch project we might help you.

Hello !
I have the same problem, I think it is better to ask here instead of creating a new topic

here is the code in the ‘Server.js’ file :

'use strict';

var express     = require('express');
var bodyParser  = require('body-parser');
var expect      = require('chai').expect;
var cors        = require('cors');

var apiRoutes         = require('./routes/api.js');
var fccTestingRoutes  = require('./routes/fcctesting.js');
var runner            = require('./test-runner');

var app = express();

app.use('/public', express.static(process.cwd() + '/public'));

app.use(cors({origin: '*'})); //For FCC testing purposes only



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

//Sample front-end
app.route('/:project/')
  .get(function (req, res) {
    res.sendFile(process.cwd() + '/views/issue.html');
  });

//Index page (static HTML)
app.route('/')
  .get(function (req, res) {
    res.sendFile(process.cwd() + '/views/index.html');
  });

//For FCC testing purposes
fccTestingRoutes(app);

//Routing for API 
apiRoutes(app);

//404 Not Found Middleware
app.use(function(req, res, next) {
  res.status(404)
    .type('text')
    .send('Not Found');
});

//Start our server and tests!
app.listen(process.env.PORT || 3000, function () {
  console.log("Listening on port " + process.env.PORT);
  if(process.env.NODE_ENV==='test') {
    //console.log('Running Tests...');
    setTimeout(function () {
      try {
        //runner.run();
      } catch(e) {
        var error = e;
          console.log('Tests are not valid:');
          console.log(error);
      }
    }, 3500);
  }
});

module.exports = app; //for testing

And here is the code inside the ‘api.js’ file :

'use strict';

var expect = require('chai').expect;
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;

const CONNECTION_STRING = process.env.DB; //MongoClient.connect(CONNECTION_STRING, function(err, db) {});

module.exports = function (app) {
  
  MongoClient.connect(CONNECTION_STRING, { useNewUrlParser: true}, (err, client) => {
    if (err){
      console.log('Database Error ' + err); 
    } else {
      const db = client.db('fcc_issuetrckr');
      app.route('/api/issues/:project')

        .get(function (req, res){
          var project = req.params.project;
        res.send(project);
        })

        .post(function (req, res){
          var project = req.params.project;
          db.collection(project).insertOne({
            issue_title: req.body.issue_title,
            issue_text: req.body.issue_text,
            created_by: req.body.created_by,
            assigned_to: req.body.assigned_to || '',
            status_text: req.body.status_text || '',
            created_on: new Date(),
            updated_on: new Date(),
            open: true
          }, (err, doc) => {
            if (err){
              console.log('database err' + err); 
            }
          });
        })

        .put(function (req, res){
          var project = req.params.project;

        })

        .delete(function (req, res){
          var project = req.params.project;

        });
    }
  });
};

If I try to get ‘/api/issues/myproject’ , I get the ‘Not found’ response instead of the name of the project ‘myproject’
But if I remove the 404 middleware that works fine.

1 Like

Hello, I may have found the answer to your problem, at least I found something that worked for me and may help someone else.

If you place the ‘Not found’ middleware below your other routes, it will work as planned. Node.js will go through all routes in order, and only fire the ‘not found’ middleware if it doesn’t find a match.

2 Likes