[Express] Level 2: Middleware -- 1

Mounting Middleware

Given an application instance is set to the app variable, which of the following function calls would you use to mount a middleware called logger ?

Answer: 

app.use(logger);

 

Default Middleware

What is the only middleware that's shipped with Express 4?

Answer: express-static

 

Express Static

Change the code in app.js to use the express-static middleware instead of the response.sendFile() function.

复制代码
var express = require('express');
var app = express();

app.get('/', function (request, response) {
  response.sendFile(__dirname + '/public/index.html');
});

app.get('/cities', 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');
});*/

//cd public
app.use(express.static('public'));

app.get('/cities', 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 thejquery.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 in the client.js file, complete the code for the $.get function so that it calls the /cities URL path, and then runs the appendToList function.

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Cities</title>
</head>
<body>
  <h1>Cities</h1>

  <ul class='city-list'></ul>
   <script src="jquery.js"></script>
   <script src="client.js"></script>
</body>
</html>
复制代码

Now in the client.js file, complete the code for the $.get function so that it calls the /cities URL path, and then runs the appendToList function.

复制代码
$(function(){

  $.get('/cities', appendToList ); 

  function appendToList(cities) {
    var list = [];
    for(var i in cities){
      list.push($('<li>', { text: cities[i] }));
    }
    $('.city-list').append(list);
  }
});
复制代码

 

posted @   Zhentiw  阅读(383)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示