Live code steps
- Create a GitHub repo
npm initto 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 expressThere 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
- 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}`))- Go to http://localhost:5000 > cannot get because we don't have any get
- Write
App.get
app.get('/', (req, res) => {
res.send('It is a beautiful day')
});- Go to http://localhost:5000
- 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
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();
}- 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])
})app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke! ' + '\r\n' + err.message)
})