What is Express? ● Express is a web framework built on top of Node.js. ● Inspired by the Sinatra web framework. ● Helps you create modular web applications. ● Based around the concept of middleware.
Installing Node.js and Express ● Want to follow along? Get this presentation at sse.se.rit. edu/go/expresstalk. ● Install Node.js. Windows and Mac: Use the Installer from nodejs.org/download. Linux: Look for “node” in your package manager or build it from source. ● Install Express. Run npm install express in the directory where you want to put your app.
Hello World 1. Create app.js. var express = require('express'); // load the Express module var app = express(); // create a new Express app // Respond to requests for / with “Hello World!”. app.get('/', function (request, response) { response.send('Hello World!'); }); // Start a server with the Express app on port 3,000. var server = app.listen(3000, function () { console.log('Example app listening at http://localhost:3000/'); });
Hello World 2. Run node app.js. 3. Open http://localhost:3000 in your web browser. 4. If you want to create a package.json for sharing your app and installing dependencies, run npm init.
Middleware ● A function executed by the Express router after a request but before the final route. ● Middleware can be used for logging, error handling, template rendering, routing, etc.
Using Middleware ● Express’s app.use() can be passed your own middleware function or a function from a middleware library to add it to all requests. ● In your middleware function, you must call next() when you’re done to let other middleware run (unless you want to end the middleware stack). ● Order matters!
Using the Express Generator 1. Install the Express app generator a. npm install express-generator -g 2. Use the generator to create a new app a. express --ejs example b. cd example c. npm install 3. Edit your app however you’d like and run it with npm start.
Useful npm Commands ● npm install Installs all your dependencies. ● npm install --save Installs a specific package and saves it to your dependencies. ● npm start Runs your app. ● npm test Runs your tests (if you have a test script in package.json).
FAQ ● What about models? Express doesn’t have models. You can set up model objects yourself or use a library. ● Is it production ready? Yes, it is used in production by many large organizations. ● What CSS preprocessors and templating engines are supported? The Express app generator supports several including ejs, jade, and less, but you can use pretty much anything that conforms to Express’s templating APIs.