27-03-2019
import express from 'express'
const app = express()
app.get('/', (req, res) => res.send('My response'))
app.listen(3000, () => console.log('Example app listening on port 3000!'))
import express from 'express';
const myMiddleware = function(req, res, next) {
// ... do whatever I need with req and res
next() // ensure the next middleware in the chain is invoked
}
const app = express();
app.use(myMiddleware);
In this exercise you'll be creating a simple Express based API in node that returns "Hello World" and logs the requests.
git clone https://gitlab.com/jmarques/api-design-nodejs.git
git checkout exercise-1
app.get('/route', (req, res) => { ... })
app.get(/.*fly$/, (req, res) => { ... })
app.get('/route/:routeId', (req, res) => {
// req.params: { routeId: '<value>' }
})
In this exercise you'll be creating two different routes to access two different sets of data: posts and users
git checkout exercise-2
resources/users
file to access the list of usersresources/posts
file to access the list of posts
app.get('/route', (req, res) => { ... })
app.post('/route', (req, res) => { ... })
app.patch('/route', (req, res) => { ... })
// OR
app.route('/route')
.get((req, res) => { ... })
.post((req, res) => { ... })
.patch((req, res) => { ... })
// in users.js
const router = express.Router()
router.get('/', (req, res) => { ... })
router.get('/:username', (req, res) => { ... })
router.post('/', (req, res) => { ... })
export default router
// in server.js
import userRouter from './users'
app.use('/users', userRouter')
In this exercise you'll be expanding on the previous exercise to implement a full CRUD on two different sets of data: posts and users
git checkout exercise-3
npm i -S body-parser
resources/users
resources/posts
import jwt from 'jsonwebtoken'
import expressJwt from 'express-jwt'
const claims = {
username: 'myUser',
exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour
}
// to generate a token
const token = jwt.sign(claims, 'my precious')
// to verify a token
const decoded = jwf.verify(token, 'my precious')
app.use('/myPath', expressJwt({ secret: 'my precious' }).unless({ path: <unprotected paths here> })
In this exercise you'll be securing the application with JWT
git checkout exercise-4
npm i -S jsonwebtoken express-jwt bcrypt