Express4 Flashcards
(19 cards)
Create an Express application (bare bones)
var express = require("express"); var app = express();
// routes
app.listen(5000);
Configuration settings (9 of them, names and brief description of what they do)
- “env” Environment mode, defaults to process.env.NODE_ENV (NODE_ENV environment variable) or “development”
- “trust proxy” Enables reverse proxy support, disabled by default
- “jsonp callback name” Changes the default callback name of ?callback=
- “json replacer” JSON replacer callback, null by default
- “case sensitive routing” Enable case sensitivity, disabled by default, treating “/Foo” and “/foo” as the same
- “strict routing” Enable strict routing, by default “/foo” and “/foo/” are treated the same by the router
- “view cache” Enables view template compilation caching, enabled in production by default
- “view engine” The default engine extension to use when omitted
- “views” The view directory path, defaulting to “process.cwd() + ‘/views’”
- “x-powered-by” Enables the X-Powered-By: Express HTTP header, enabled by default
Set a configuration
app.set(name, value);
Get a configuration. What is returned when not yet set?
app.get(name);
Returns undefined
if not set
Set configuration to true, set to false
app. enable(name);
app. disable(name);
Check if configuration value is true, or false
app. enabled(name);
app. disabled(name);
What is middleware likened to? What are important considerations?
FINISH FROM ROUTES SECTION
Talk about “pipe line”, “sequentially run”, etc.
Middleware is run sequentially, so order of middleware is crucial.
Add middleware to application. What is the optional argument and what is it’s default?
app.use(function (req, res, next) { // middleware statements goes here });
Default argument (which comes first if present) is the “mount path”, which defaults to root “/”.
app.use("/admins", function (req, res, next) { // login requirement });
Server static files
app.use( express.static( __dirname + “/path/to/public” ) );
Can middleware functions see what path they were mounted to? Why?
What happens to req.url
in this situation?
No. Because it makes your apps agnostic of where they are mounted to, that way they can be used more independently and don’t require code changes when code outside of the middleware changes.
req.url
has the mounted prefix stripped from it for just this mounted middleware.
Register a template engine to handle certain file extensions. Change the default template engine. What does this do?
// register all .jade files to use Jade template engine
app.engine(“jade”, require(“jade”).__express);
// change default template engine
app.set(“view engine”, “jade”);
// Now when you call the following, it will assume .jade app.render("file-name");
// Render HTML files using jade
app. engine(“html”, require(“jade”).__express);
app. set(“view engine”, “html”);
Middleware for dynamic route parameters. Different argument types?
Is the parameter middleware always run?
// middleware called when route has :name app.param("name", function (req, res, next, name) { // do something with name, then call next(); });
// you can also use regex to validate parameters app.param("name", /^[A-Z]+$/);
No, it is only run when the a route is called that uses the parameter.
Routing methods (HTTP Methods). Argument options. Dynamic path elements, option path elements, etc.
app.get(“/route”, function (req, res) { … });
// methods for all http methods, including:
app.post
app.put
app.del – More proper to use del
instead of delete
// method-agnostic
app.all
// dynamic and option path elements app.get("/path/:dynamic/:optional?", ... );
// You can also use regex as the path app.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function ... );
// you can also pass in multiple callbacks as arguments app.get("/admins", user.loadMiddleware, function ...);
// or you can use .all() to provide common callbacks for all method types on that path app.route("/admins") .all(user.loadMiddleware) .get(function ... ) .del(function ... );
// you can also use *
to have global matching, which can be super useful, like:
app. all(“/admin/”, authenticateMiddleware);
app. patch(“”, badMethodError);
Method to avoid having duplicate route-path strings
app.route() returns an instance of a single route, so you can do this:
app.route("/path") .all( loadDependencies ) .get(function ... ) .post(function ... ) ...
Provide app-level helper methods and variables to all view-templates. What is included by default?
app.locals object.
app.locals.title = “App”;
app.locals.formatTime = function (timestamp) {
return …
};
Settings are included by default. So: app.set("views", "/path/to/views"); app.render("index"); // index.? {{settings.views}} => /path/to/views
Application view render
app.render(“view-template”, { custom-data }, function (err, html) { … });
Object containing properties mapped to the “named route parameters”. Give example. What happens if there aren’t any named route parameters?
req.params
/admins/:name => {name}
/admins => { } (empty object if there aren’t any)
Adding methods to request or response objects. Best practice and why? How does methods access the actual request or response instance objects?
You could have middleware add to the req and res objects, but that would be slower and less memory efficient than adding properties or methods to the request/response prototype objects, like so:
var express = require("express"); var res = express.response; // response *prototype*
res.method = function() { // this method conserves memory since it's a member of prototype // this method can access members of a specific request via: var locals = this.req.locals; // notice "this" var contentType = this.get("Content-Type"); };
Notice that res.get
uses this.get
but req.locals
uses this.req.locals
. The reason is because this
is equal to the object you are adding a method to; so if you’re adding a method to the request object, this
is already equal to the request object so you can call methods that belong to req directly on this
; if you need to access the other side (like referencing the response object while in a request method), you can use this.req/res
.
Strategies during app loading
Loading the application is not like handling every request. The more you do during application loading, the less you need to do for each request. Therefore, only do things during each request that are particular to the request itself. For example, don’t add methods to the response instance, add them to the response prototype, which not only conserves memory but the logic of creating the method is only run when the app is loading.
Similarly, keep “require()” calls and other synchronous calls outside of middleware and position it where it can be called during application loading.