Expresso capstone Suprising body-parsing glitch causes test failure

I’m trying to understand why this caused a failure…
When writing the POST route (the first one that uses info in the body of the request) , I could not get it to pass the tests. It kept saying that the information in the body was undefined. After several hours, I narrowed it to the server.js file and the order in which I had the require and .use statements!

My code was like this when getting the error:

const express = require('express');
const app = express();

const apiRouter = require('./api/api.js');
app.use('/api', apiRouter);

const PORT = process.env.PORT || 4000;

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); // if body is sent through URL
const cors = require('cors');
app.use(cors());
const errorhandler = require('errorhandler');
app.use(errorhandler());
const morgan = require('morgan');
app.use(morgan('dev'));

app.listen(PORT, () => {console.log('listening on port: ' + PORT);});
module.exports = app;

Notice that the app.use('/api', apiRouter); is before the .use for the body-parser?

When I moved the code:

const apiRouter = require('./api/api.js');
app.use('/api', apiRouter);

to the end of the file, just before the app.listen statement, the program worded and all test passed!

So, now I’m trying to understand the reason this works…
Is it because the app.use('/api', apiRouter); being processed first caused routing to happen before the implementation of the other middleware?
Does none of the middleware get used at all under this structure?
It seems like this would be an important fact to point out.

Any clarification on this would be great.
Thanks

Correct. Since you put your router before all the middleware and your router responds to the client (and doesn’t call next()), then it doesn’t continue to the other middleware. You’ll notice that the morgan middleware wasn’t logging anything to the console too.

It was more obvious here because body-parser didn’t get to do it’s job, so it never attached anything to req.body

It’s definitely pointed out in the lesson materials along the way, but in the presence of so much new information, it’s easy to miss or forget the significance of something. Projects like this are a great way to practice and run into situations like this that cause you to dive deeper into something. You’ll now have the experience to look for this kind of thing in the future.

1 Like