Using Express
Hello World Example
var express = require('express');
var app = express();
// on GET request to the url
app.get('/todos', function(req, res) {
});
// on POST request to the same url
app.post('/todos', function(req, res) {
});
// start server on port 3000
app.listen(3000);
A server with two routes."The
req
and res
objects have a lot of power". You modify and mutate them through your app.A more complicated example for a todo app:
var todos = [];
app.get('/todos', function(req, res) {
// send back a json response
res.json(todos);
});
app.post('/todos', function(req, res) {
var todo = req.body.todo;
todos.push(todos);
// res.send converts to json as well
// but req.json will convert things like null and undefined to json too although its not valid
res.send(todo);
});
// get the parameters from the route
app.get('/todos/:id', function(req, res) {
var todo = _.find(todos, {id: req.params.id});
res.json(todo);
});
It will even concert null or undefined to JSON.Uses lodash to work with the todo collection.
Very simple but powerful.
You can define more than one function per request type: that's a middleware.
If you do the same on GET and POST you're not adhering to REST.
Middleware
To inspect and modify incoming requests. It's just a function, like above a callback.
A middleware will inspect the
req
object, act on it (or not) than pass to the next middleware. Or it can even stop the flow and send back immediately.Routing and middleware are the two most important features of Express. Express is only 1 page long code.
All middleware are available as third-party libs.
Express can serve very well static assets. Chunks, reading files in buffers, etc.