NodeJS
Crash course
03
PAY Namibia 2018
ExpressJS
What is it?
- NodeJS framework
- Bunch of useful features
- Fast and productive development
Instalation
npm install express --save
const express = require('express');
let app = express();
app.get('/', (req, res) => {
res.send('Hello Express')
});
app.listen(process.env.PORT || 3000)
Reading query params
https://localhost:3000?name=Dusan&last=Stankovic
app.get('/', (req,res)=>{
res.send(req.query);
});
Checkpoint #1
Pass two numbers and operation in query parameters and return value.
E.g.
localhost:3000?operation=sum&a=4&b=10
returns 14
Showing static files
app.use(express.static(__dirname + "/public"));
localhost:3000/public/1.png
Midleware
app.use(express.static(__dirname + "/public"));
a function that has access to request, response and next middleware function.
app.use((req, res, next) => {
// do something with req or response
//call next middleware function
next();
});
Checkpoint #2
Pass 4 numbers in a query string and create 4 middlewares doing a basic arithmetic operation.
E.g. for url: localhost:3000?init=1&a=3&b=10&c=2&d=3
should result in: -4
Explanation:
init state = 1;
1st middleware: 1+3 = 4
2nd middleware: 4-10 = -6
3rd middleware: -6 * 2 = -12
4th middleware: -12/3 = -4
nodeschool.io
NodeJS crash course - 03
By Dušan Stanković
NodeJS crash course - 03
ExpressJS
- 1,074