CS174
Chris Pollett
May 3, 2017
npm install express-generator -g
express -h
express --view=pug test_app
create : test_app create : test_app/package.json create : test_app/app.js create : test_app/public create : test_app/routes create : test_app/routes/index.js create : test_app/routes/users.js create : test_app/views create : test_app/views/index.pug create : test_app/views/layout.pug create : test_app/views/error.pug create : test_app/bin create : test_app/bin/www create : test_app/public/javascripts create : test_app/public/stylesheets create : test_app/public/stylesheets/style.css install dependencies: $ cd test_app && npm install run the app: $ DEBUG=test-app:* npm start create : test_app/public/images
cd test_app npm install
DEBUG=myapp:* npm start #Alternatively use: node ./bin/wwwFrom a Windows (command or power) shell type:
set DEBUG=myapp:* & npm start
var index = require('./routes/index'); var users = require('./routes/users'); //... app.use('/', index); app.use('/users', users);Set up that the "/" and "/users" routes should be handled via the modules in ./routes/index.js and ./routes/users.js
// view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug');
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); module.exports = router;
extends layout block content h1= title p Welcome to #{title}
To create our own custom apps using the express generated code:
app.js /media /node_modules package.json /public
var express = require('express') var app = express() app.use('/media', express.static(__dirname + '/media')); app.use(express.static(__dirname + '/public')); // routes from last day app.get('/', function (req, res) { res.send('This is an express app using route /') }) app.get('/foo', function (req, res) { res.send('Foo route ') }) app.listen(8888, function () { console.log('Server up!') })
app.METHOD(PATH, HANDLER)
var bodyParser = require('body-parser'); app.use( bodyParser.json() ); // this is needed if json data posted (not really current case) app.use(bodyParser.urlencoded({ // this is needed for usual form posted data extended: true })); app.post('/foo-post', function (req, res) { res.send('Foo data '+ req.body.foo) });