Mounting middleware
Given An application instance app
are set to the variable, which of the following function calls would Middleware called logger ?
Answer:
App.use (logger);
Default Middleware
What's the only middleware this ' s shipped with Express 4?
Answer:express-static
Express Static
Change the app.js
express-static Middleware instead of the response.sendFile()
function.
var express = require (' Express '); var app = Express (); App.get (function (request, Response) { + '/public/ Index.html ');}); App.get (function(req, res) { var cities = [' Lotopia ', ' Caspiana ', ' Indigo ' ]; Res.send (cities);}); App.listen (3001);
Remove our app.get()
containing the root ‘/‘
route.
Mount the static
middleware and serve files under the public directory.
Answer:
var express = require (' Express '); var app = Express (); /* app.get ('/', function (request, response) { response.sendfile (__dirname + '/public/index.html ');}); */ // CDPublic app.use (express.static (' public ')); App.get (function(req, res) { var cities = [' Lotopia ', ' Caspiana ', ' Indigo ']; Res.send (cities);}); App.listen (3001);
Script Tags
Now we can add some client side JavaScript by including the jquery.js
and client.js
files.
Within index.html
, include jquery.js
using a <script>
tag.
Within index.html
, include client.js
using a <script>
tag.
Now on client.js
the file, complete the code for $.get
the function so it calls /cities
the URL path, and then runs the function.
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Cities</title></Head><Body> <H1>Cities</H1> <ulclass= ' city-list '></ul> <Scriptsrc= "Jquery.js"></Script> <Scriptsrc= "Client.js"></Script></Body></HTML>
Now on client.js
the file, complete the code for $.get
the function so it calls /cities
the URL path, and then runs the function.
$ (function() { $.get ('/cities ', appendtolist); function Appendtolist (cities) { var list = []; for (var in cities) { List.push ($ (' <li> ', {text:cities[i]}); } $ ('. City-list '). Append (list); }});
[Express] Level 2:middleware--1