
// -------- app.js ---------
let express = require('express');
let app = express();
app.get('/', (req, res, next) => {
res.send('Hello World!');
});
app.get('/john', (req, res, next) => {
res.send('Hello, John!');
});
app.listen(3000);
$ mkdir demo; cd demo // create demo directory
$ npm init -y; npm install express // install express
$ node app.js // run app.js
app.method(path, handler)app.get('/john', (req, res, next) => { res.send('Hello, John!'); });
handler for a request sent to path (exact match, not prefix) via methodapp.all(path, handler) to handle all methodsapp.get('/dogs/:breed', (req, res, next) => { res.send(req.params.breed); });
:breed makes the matching substring available as a “parameter”req.params like req.params.breedpathpath at https://www.npmjs.com/package/path-to-regexpTakes three parameters: request, response, next
request: information on the HTTP request
req.app: express app that received the requestreq.body: request bodyreq.query: (URL) query name value pairsresponse: response to be sent to the client
res.send("hello, there!")next: the next handler to be called on the request in the request handling chainnext() exits from the current handler and moves on to the next in the chainnext() is not called, the request processing stops there, ignoring the rest in the chainresponse to the handlerres.status(200)res.append(field, value)res.redirect([status,] URL)
res.redirect('/')res.send(body)
body as the responseres.send("Hello, world!")res.sendFile(absolute_path)
res.sendFile('/User/cho/public/index.html')res.json(object)
object in JSONres.json({title: "Hello", body: "_Love_"})res.render(template-file, template-data)
template-file using template-datares.render("index", {title: "Hello"})$ npm install ejs
<% ... %>: javascript for control-flow. no output<%= ... %>: print out the result of expression (after HTML escaping)<%- ... %>: print out the result (raw output. No HTML escaping)<!-- index.ejs --->
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body>
<ul>
<% for (let post of posts) { %>
<li><%= post.title %></li>
<% } %>
</ul>
</body>
// ---- app.js ------
let express = require('express');
let app = express();
app.set('view engine', 'ejs'); // template engine to use
app.set('views', '.') // view template directory
app.get('/', (req, res, next) => {
res.render("index",
{ title: "Hello",
posts: [{title: "Title 1"}, {title: "Title 2"}]
}
);
});
app.listen(3000);
/birds
/sparrow
/dove
/dogs
/bulldog
/shepard
app.use([path,] middleware) for prefix routing
path is interpreted as a prefix not exact match
path prefix is removed in req.path passed to middleware (except ending / if exists)middleware is a fancy name for request handlerfunction birds() { ... }
function dogs() { ... }
let express = require('express');
let app = express();
app.use('/birds', birds);
app.use('/dogs', dogs);
app.listen(3000);
/birds and /dogs are almost like “mini web sites!”express.Router() to create a “mini web site”
Router() per prefix, and “mount” them on the corresponding prefixRouter, use router.METHOD(subpath, callback) to handle subpathRouter is like a “mini Express app”express.Router() Example// create a router
let birds = express.Router();
birds.get('/sparrow', (req, res, next) => res.send("Sparrow"));
birds.get('/dove', (req, res, next) => res.send("Dove"));
// mount the router at a prefix
app.use('/birds', birds);
use() to create “mini mini (?) web site”express.static(absolute_path_to_root_dir)
body-parser package
bodyParser.json(): parser for JSON bodylet express = require('express');
let path = require('path');
let bodyParser = require('body-parser');
let app = express();
app.use('/json', bodyParser.json());
app.use('/www', express.static(path.join(__dirname, 'public')));
app.listen(3000);
next(err) to get into “error handling mode”
next(err) is called
next() (no parameter) moves on to the next request handlernext(err) (single parameter) moves on to the error handlercallback(err, req, res, next)err is what was passed in the call next(err)err passed to next(err)app.use((err, req, res, next) => {
res.status(404);
res.send(err + ": John not found error!");
});
next(err)$ mkdir demo; cd demo
$ express --view=ejs // generate skeleton code with EJS template engine
$ npm install // install dependent modules
$ npm start // execute "start" script in package.json
app.js: main applicationpublic/: folder for static filesroutes/: route handling middlewareviews/: view template files