Architecture and setup of a basic Express application
Express:
- A framework for building web servers in Node.js.
- Reads and interprets HTTP requests from clients.
- Passes a request through functions (middleware) to process the request.
- Responds to a client with information and data resolutions.
Architecture:
Express combines middleware to modify request data
express()
- is the top-level function that creates the Express application and allows access to the 4 Express objects:
- Application -
app
- Exposes the methods to handle HTTP requests, allows configuration of middleware and much more. - Request -
req
- An object with properties describing the request from a client (url, domain, host, port, headers, body, etc. ) - MDN. - Response -
res
- An object with properties describing the response sent to a client from the server -> It includes methods for handling routing, setting the status/headers and formatting the response. - MDN - Router - Creates modular route handlers. Referred to as a mini-app. More
Response Methods:
res.download()
res.end()
res.json()
res.jsonp()
res.redirect()
res.render()
res.send()
res.sendFile()
res.sendStatus()
Express SETUP
- create a new project directory
- inside new directory ->
npm init
- create a new file inside new directory ->
app.js
-
create a script in package.json:
"script": { "start": "node app.js" }
npm install express
-
In app.js add to top of file:
const express = require('express');
-
Invoke the Express function and assign it to app:
const app = express();
-
Test the root route -> create a function:
app.get('/', (req, res) => { res.send('Hello World!'); });
-
Create a listening function:
app.listen(8000, () => { console.log('Express server is listening on port 8000!'); });
npm start
- Go to localhost:8000 to see 'Hello World!"
The complete app.js looks like this:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World.');
});
app.listen(8000, () => {
console.log('Express server is listening on port 8000!');
});