https://www.npmjs.com/package/express
One of the most popular libraries to build server with node.
express()
- const app = express()
listen()
- app.listen(3000)
GET
request in Expressapp
- an instance of expressMETHOD
- HTTP request methodPATH
- path on the serverHANDLER
- function executed when route is matched\Content type is automatically converted:
text/HTML
application/JSON
is also automatically converted
.use()
- a generic express middleware
next()
- In order for the middleware to keep passing through, it needs to call: next()
The way middleware works:
app.use()
gets the request of the websitenext()
and express keeps running through the rest of the codeMiddleware: Something that receives ahead of time before getting through the routes.
body-parser
as a middlewareIf we want to access req.body
, we need to use a middleware: body-parser - npm (npmjs.com), it will grab anything it receives and parse it
💡Express Version Update
If you are running a version of Express that is 4.16+, it now includes the same functionality inside of Express. Instead of adding these lines in the code like:
app.use(bodyparser.urlencoded({extended: false}));
app.use(bodyparser.json());
If you are using Express 4.16+ you can now replace that with:
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(express.json())
Most used properties of request:
?key1=value1&key2=value2
app.use()
middleware to send it to the body:id
If there are more than 1 params e.g. /user/:name/:date
, req.params will return an object.
?q="hello"
Most used properties of response
res.status(404)
public
folderpublic
folder, create an index.html
fileexpress.static()
__dirname
does not work in ES modules.
Solutions:
hello.txt:
script.js:
const fs = require('fs');
- access the fs
modulefs.readfile()
''
- path(err, data) ⇒ {}
- function with err
and data
parameters.toString()
.toString('utf8')
: type of encoding, mostly used in webfs.readFileSync(’./hellotxt’)
readFile()
vs. readFileSync()
readFile()
is async: will continue to read through the file, and until it’s done it will continue execute the callback functionreadFileSync()
is sync: will block the file until it’s donescript.js:
hello.txt:
created a new file: bye.txt
→ bye.txt is removed