First, you are not even requiring express
, you are requiring a JSON file, so you should change that first line to:
const express = require('express');
Then, you need to call app.listen
once you are done setting up your middleware, which you might be doing in a different file, but it's worth mentioning it.
So, all together with a few other small changes:
// Why?
// const express = require('./data.json');
// It should be like this instead:
const express = require('express');
// And if you want to require a JSON file anyway to send it back:
const data = require('./data.json');
// Require morgan:
const morgan = require('morgan')
// Create the express app:
const app = express();
// Use morgan's middleware in your express app:
app.use(morgan('combined'));
// Define the port to run the server at:
const port = 3000;
// Define your GET / route:
app.get('/', (req, res, next) => {
// Send status code + text message:
res.status(200).send('USER');
// Or if you prefer to send JSON data:
// res.status(200).json(data);
});
// Start listening on that port:
app.listen(port, () => console.log(`App listening on port ${ port }!`));
If you run this with node <filename>.js
after installing all the dependencies, you should see a message like App listening on port 3000!
and then morgan
will log a message for every incoming request automatically.
Note you can export your app instead of calling app.listen(...)
at the end of the file with module.exports = app
, but in that case you need to import that somewhere else (maybe you have a server.js
file or something like that) and then call app.listen(...)
there.