- Describe how a client interacts with a server
- Explain what ExpressJS is and why it is useful
- Use middleware in an Express application
- Use middleware with routes and HTTP verbs
- What is the flow of information between the client and the server? What are the names and parts?
Given the following examples of a web server written with Node http and Express that perform the same tasks
const fs = require('fs')
const http = require('http')
const server = http.createServer(function(request, response) {
if(request.url === '/logo.png') {
response.writeHead(200, {'Content-Type': 'image/gif'})
fs.readFile(__dirname + '/public/logo.png', function(err, data) {
if(err) console.log(err)
response.end(data)
})
}
else if (request.url === '/'){
response.writeHead(200, {'Content-Type': 'text/html' })
fs.readFile(__dirname + '/public/index.html', function(err, data) {
if(err) console.log(err)
response.end(data)
})
}
}) // and much more besides
const express = require('express')
const http = require('http')
const app = express()
app.use(express.static('./public'))
app.get('/', function(req, res, next) {
res.sendFile('./public/index.html')
})
http.createServer(app).listen(3000)
console.log('Express server is listening on port 3000')
- What are the tasks performed?
- What parts are of the process does Express help you with
- What is middleware?
- Why is middleware useful?
- What arguments does a middleware take?
- How is middleware added to an express application?
- What does the following middleware do?
const express = require('express')
const http = require('http')
const app = express()
app.use(function(req,res, next){
console.log(`Request: ${req.method} at ${req.url}`)
next()
})
http.createServer(app).listen(3000)
console.log('Express server is listening on port 3000')
- How would you make the middleware only run on a specific route?
- What are HTTP verbs? What are some examples?
- What part of the client server communication do they belong in?
- How would you add a middleware the matches a route with a specific HTTP verb?
- Fill in the blank, create the middleware, no need for actual code to handle actions
- Create a route to get all users
- Create a route to create a user
const express = require('express')
const http = require('http')
const app = express()
/*
Your code goes here
*/
http.createServer(app).listen(3000)
console.log('Express server is listening on port 3000')