Express Is Adorbs
Express is adorable. It’s the tiniest, cutest little web framework.
Besides adorable, Express is a lightweight web framework for Node.js. It addresses a few basic needs of Node applications.
|need to implement whole HTTP server||convenience methods for easy-to-start server|
|need a router to map requests to request handlers||routes requests to designated handler based on HTTP verb + path|
|need to actually handle requests||callbacks handle requests!|
A “hello world” Express server is very simple. Besides the standard
node_modules (libraries) that come with a new Node project, here’s all it took:
$ npm install express --save
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
That’s all there is to it. Run
node app.js on the command line, open up localhost:3000 in a browser, and you’re all set.
req (the arguments passed into each callback) are pretty powerful objects. Built on Node’s own response and request objects, these objects come with helpful methods to read the request or alter the response body.
For example, you can have the response send back JSON instead of a regular String:
1 2 3
I really like the simple route layout that Express encourages. Each route is a simple combination of HTTP verb + path. (A REST best practice, incidentally: keep the URL the same but vary the verb.)
In the following example, when we load and submit an HTML form, we hit two different
1 2 3 4 5 6 7 8 9 10 11 12 13
Hello, World (of Express)!