Working from here: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs
Express/ Node Introduction
Introducing Node
- Node – open source, cross platform, runtime environment.
- Creates all kinds of server-side tools
- Uses JavaScript.
- Outside a browser context – basically running directly on a computer or server.
- Great performance, plain JS, NPM – packages, portable
- Active community
- Hello Node.js
- Simple web server
- Listens for any kind of HTTP request at http://127.0.0.1:8000/
- When a request is received, responds with ‘Hello World’
- This is the code to make that happen:
const hostname = "127.0.0.1";
const port = 8000;
// Create HTTP server
const server = http.createServer((req, res) => {
// Set the response HTTP header with HTTP status and Content type
res.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body "Hello World"
res.end('Hello World\n');
});
// Prints a log once the server starts listening
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
})
- To make this run, we run:
node hello.js
- Then go to http://localhost:8000
Web Frameworks
- Other common web dev tasks – not directly supported by Node itself.
- E.g Get, POST, DELETE – (i.e routes) – or templates or static files, we need to use a web framework.
Introducing Express
- Express – most popular node web framework.
- Library for lots of other frameworks, too
- Mechanisms to:
- write handers for requests and routes
- Integrate with view rendering engines
- Set common web settings like the port to use for connecting
- Add additional processing with middleware anywhere in the response request pipeline
- Express is fairly minimalist
- Develpos have created lots of middleware packages to address almost any web dev issues.
- Express is unopinionated – can insert any compatible middleware you like into the request handling chain.
- Structure the app any way you like.
What does Express Look Like?
- Traditional data-driven website, web app waits for a HTTP request. Request received, works out what action is needed based on the pattern. Then read or write information from a a database etc. Then return a response to the web browser – usually by creating an HTML page for the browser to display the retrieved datas.
- Helloworld Express
- This is an example of a basic hello world app.
- Can do this by calling node ./app.js
- Don’t forget to install express – npm install express
- This is the code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`)
});
- Importing and creating modules
- Module is a JS library/ file that you can import into other code using Node’s require() function.
- Express – example of a module.
- Also middleware and database libraries.
- We import modules using the require keyword.
- Then we call it to create an app (see above)
- Then we can access the properties and functions of the application object.
- Can also create your own modules, and import them in the same way.
- Using Asynchronous APIs
- JS code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete.
- Synchronous API – one in which each operation must complete before the next operation can start.
- Async – start an operation and immediately return to the stack before the operation is completed.
- Most common way – callbacks, but can lead to callback hell.
- Common – error first call-backs.
- Can also use things like async modules, or promises.
- Creating route handlers
- The app.get function is an example of a callback function.
- It takes a request and response object as arguments.
- Calls send upon response.
- Can group route handlers for a particular part of the site together – e.g. /wiki/
// wiki.js - Wiki route module
const express = require('express');
const router = express.Router();
// Home page route
router.get('/', function(req, res) {
res.send('Wiki home page');
});
// About page route
router.get('/about', function(req, res) {
res.send('About this wiki');
});
- Using middleware
- Used extensively in Express apps – serving static files, error handling compressing HTTP responses.
- If a middleware does not end the req, res circle, it must call next to pass control to the next middleware function.
- Middleware and routing functions – called in the order they are declared.
- For some middleware, the order is important.
- Can write own middleware functions – often for handling errors.
- Really own difference to call-backs is that they have a third argument – next.
- Serving static files
- Can use express.static to serve static files, including images, CSSS.
- This is actually the only middleware function that is part of Express.
- Handling errors
- Four errors, instead of the usual three.
- Using databases
- Express apps can
- Need to use a database driver – e.g. npm install MongoDB
- Can be installed locally or on a cloud server.
- Rendering data (views)
- Use template engines
- Basically tell express where etc look for the templates.
- Need to install the package containing templates library too.