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