Install Express
npm install -g express
express --sessions --css less --ejs myapp
cd myapp && npm install
node myapp
{
"name": "myapp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.0",
"ejs": "*",
"less-middleware": "*"
}
}
/*
* GET users listing.
*/
exports.list = function(req, res){
res.send("respond with a resource");
};
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
app.set('title', 'Javascript Everywhere');
app.get('title');
// => "Javascript Everywhere"
app.enable('trust proxy'); app.get('trust proxy'); // => true
app.disable('trust proxy');
app.get('trust proxy');
// => false
// all environments
app.configure(function(){
app.set('title', 'Fancy Web App');
})
// development only
app.configure('development', function(){
app.set('db uri', 'localhost/dev');
})
// production only
app.configure('production', function(){
app.set('db uri', '255.255.255.255/prod');
})
Initialize your view engine (in this case - EJS)
app.set('view engine', 'ejs');
Equivalent to:
app.engine('ejs', require('ejs').__express);
// Check that a unique token is present in a request
function checkForCsrf(req,res,next) {
//use param, e.g., if token is valid proceed with next();
if(req.param("_csrf") === req.csrfToken) {
next();
} else {
next("Invalid CSRF token")
}
});
function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
};
app.use(function(req,res,next) { // checkForCsrf
//use param, e.g., if token is valid proceed with next();
if(req.param("_csrf") === req.csrfToken) {
next();
} else {
next("Invalid CSRF token")
}
});
app.get("/json", function(req, res) {
res.json({
x: "A variable!",
y: 1,
z: true
});
});
app.get("/documents/:id", function(req, res) {
// Nothing found!
res.send(404);
});