Skip to content

Latest commit

 

History

History
119 lines (103 loc) · 3.02 KB

File metadata and controls

119 lines (103 loc) · 3.02 KB

Express Middleware

Live code steps

Branch 1

  • Create a GitHub repo
  • npm init to create a package.json
What is Package.json? The package.json file is the heart of Node.js system. It is the manifest file of any Node.js project and contains the metadata of the project.
  • npm install express There is no need of '--save' since npm 5.0.0
  • Create index.js file
Console.log('It is a beautiful day')
  • Run Node server with the command Node index 'It is a beautiful day' should appear in the console.
  • Gitignore one liner : touch .gitignore && echo "node_modules/" >> .gitignore

Branch 2

  • Import Express: const express = require('express');
  • Create app: const app = express();
  • Install Nodemon npm i -D nodemon
What is Nodemon? Nodemon is a utility that will monitor for any changes in your source and automatically restart your server.
  • App.listen:
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`))
app.get('/', (req, res) => {
    res.send('It is a beautiful day')
});

Branch 3 - built-in Express middleware

  • Res.sendFile
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', index.html))
});
  • Create public folder, create html file
  • Copy-paste html boilerplate
  • Go to localhost and inspect - notice that it is now displaying our html file.
  • Set a static folder using an Express built-in Middleware:
app.use(express.static(path.join(__dirname, 'public')))
What is the difference between `app.get` and `app.use`?.json?

TO DO

Branch 4 - creating a logger using moment

let logger = function(req, res, next){
console.log('I am the logger');
next();
}
app.use(logger)
  • Let's try to log our url
const logger = (req, res, next) => {
	console.log(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
	next();
	}

Moment allows to parse, validate, manipulate, and display dates and times in JavaScript.

  • npm install moment
const logger = (req, res, next) => {
console.log(`${req.protocol}://${req.get('host')}${req.originalUrl}:${moment().format()}`);
next();
}

Branch 5

  • Create a file with characters (see GitHub repo: StarWars.js)
  • Create a route to access all characters
app.get('/', (req, res, next) => {
    res.send(StarWars);
    next();
})
  • Create a route to access only one character
app.get('/:id', (req, res) => {
    const char = StarWars.filter(char => char.id === parseInt(req.params.id));
    res.json(char[0])
})

Branch 6 - error handling middleware

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke! ' + '\r\n' + err.message)
})