In code-along/express-app/
Initialize a new project and install express
npm init -y
npm install --save express
Create an index.js
containing the following code:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000);
node .
Ruby on Rails
app.get(path, handlerFunction);
function handlerFunction(request, response){ //...
var server = require('express')();
server.get('/', function (req, res) {
res.send('Hello World!');
});
server.listen(3000);
var server = require('http').createServer();
server.on('request', function(req, res){
res.write('Hello World!');
res.end();
});
server.listen(3000);
This:
var app = require('express')();
var obj = require('returns-a-function')();
Is the same as this:
var express = require('express');
var app = express();
var aFunction = require('returns-a-function');
var obj = aFunction();
//http-greet-route.js
var http = require('http');
var url = require('url');
var querystring = require('querystring');
var server = http.createServer(function(request, response){
var reqUrl = url.parse(request.url);
if(reqUrl.pathname == '/'){
rootHandler(request, response);
}
else if (reqUrl.pathname == '/greet'){
greetHandler(request, response);
}
});
function rootHandler(req, res){
res.end('Hello World!');
}
function greetHandler(req, res){
var query = querystring.parse(url.parse(req.url).query);
res.end('Hello ' + query.name);
}
server.listen(3000);
//my-express-project/misc/greeter.js
var server = require('express')();
server.get('/', handleRoot);
server.get('/greet', handleGreet);
function handleRoot(req, res) {
res.send('Hello World!');
}
function handleGreet(req, res) {
res.send('Hello ' + req.query.name);
}
server.listen(3000);
Map functions to a (set of) routes
app.use(path, middleware);
function middleware(req, res, next){
//do some stuff
next();
}
var auth = require('auth-middleware');
var static = require('static-middleware');
var logger = require('log-middleware');
app.use(logger);
app.use('/assets', static('site/assets'));
app.use('/admin', auth)
/* handler functions omitted */
app.get('/', handleRoot);
app.get('/users', listUsersHandler);
app.get('/admin/home', adminHomeHandler);
app.get('/admin/users/create', userForm);
app.post('/admin/users/create', createUser);
// ...
function handler(req, res){
res.end('Hello World!');
}
function middleware(req, res, next){
//do some stuff
next();
}
app.use(path, middleware);
app.get(path, handler);
"Routes" are middleware that don't call next!
Up Next: Routes