[Express] Level 2: Middleware -- 2

Logging Middleware

Help finish the following middleware code in the logger.js file:

On the response object, listen to the event that's emitted when the response has been handed off from Express to the underlying Operating System.

  response.on('finish', function () {
    // when event finished
  });

Inside of the finish callback, calculate the duration of the request by subtracting the startTime from a new Date object. Store the duration in the duration variable, which has already been declared for you.

  response.on('finish', function () {
    duration = +new Date() - startTime;
  });

Using the stream object, which holds a reference to standard out, write the following message: "This request took ____ ms", where ____ is the duration for the request.

  response.on('finish', function () {
    duration = +new Date() - startTime;
    var message = "This request took "+duration+" ms";
    stream.write(message);
  });

If we run the code as is, the request will be stuck in our middleware. Call the function that moves processing to the next middleware in the stack.

next();

 

复制代码
module.exports = function (request, response, next) {
  var startTime = +new Date();
  var stream = process.stdout;
  var duration = null;

  response.on('finish', function () {
    duration = +new Date() - startTime;
    var message = "This request took "+duration+" ms";
    stream.write(message);
  });
  
  next();
};
复制代码

 

Add Logging Middleware

In the following code in app.js, we require our new middleware and assign it to a variable called logger.

var express = require('express');
var app = express();

var logger = require('./logger');

//TODO: mount middleware

app.listen(3000);

What function should we call in order to mount the middleware and add it to the stack?

Answer:

app.use(logger);

 

Only GET

Let's build a middleware that ensures only GET requests are allowed to go through.

First, in the only_get.js file, create an anonymous function that uses the middleware signature and assign it to module.exports. Remember, the Express middleware function signature takes three arguments.

module.exports = function(request, response, next){

};

Use the request object to check if the HTTP method used is 'GET' and if it is, then call the function that moves processing to the next middleware in the stack.

module.exports = function(request, response, next){
  if(request.method == "GET"){
      next();
  }
};

If the HTTP method is not 'GET', then complete the request by sending back a message that says 'Method is not allowed'.

module.exports = function(request, response, next){
  if(request.method == "GET"){
      next();
  }else{
      response.end('Method is not allowed');
  }
};

 

Buildings 

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

app.use(function(request, response, next){
  if (request.path === "/cities"){
    next();
  } else {
    response.status(404).json("Path requested does not exist");
  }
});

app.get('/cities', function(request, response){
  var cities = ['Caspiana', 'Indigo', 'Paradise'];
  response.json(cities);
});

app.listen(3000);
复制代码

When we run our previous code and issue a GET request to the /buildings endpoint, what will the response be?

posted @   Zhentiw  阅读(573)  评论(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工具
点击右上角即可分享
微信分享提示