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?

[Express] Level 2: Middleware -- 2的更多相关文章

  1. [Express] Level 2: Middleware -- 1

    Mounting Middleware Given an application instance is set to the app variable, which of the following ...

  2. [Express] Level 4: Body-parser -- Post

    Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express applic ...

  3. [Express] Level 3: Massaging User Data

    Flexible Routes Our current route only works when the city name argument matches exactly the propert ...

  4. [Express] Level 5: Route file

    Using a Router Instance Let's refactor app.js to use a Router object. Create a new router object and ...

  5. [Express] Level 5: Route Instance -- refactor the code

    Route Instance Let's rewrite our cities routes using a Route Instance. Create a new Route Instance f ...

  6. [Express] Level 4: Body-parser -- Delete

    Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...

  7. [Express] Level 3: Reading from the URL

    City Search We want to create an endpoint that we can use to filter cities. Follow the tasks below t ...

  8. [Express] Level 1: First Step

    Installing Express Let's start building our new Express application by installing Express. Type the ...

  9. 透析Express.js

    前言 最近,本屌在试用Node.js,在寻找靠谱web框架时发现了Express.js.Express.js在Node.js社区中是比较出名web框架,而它的定位是“minimal and flexi ...

随机推荐

  1. 第三次阅读赵炯博士的《linux内核代码完全注释》:序

    这是我第三次阅读linux内核代码完全注释了,当然前两次也没有读完,第一次读到第五章,第二次第七章. 所以说,赵炯博士对我最大的帮助时介绍了intel386的结构,以及内核编程的方法. 至于真正的内核 ...

  2. win7启动出现蓝屏STOP: 0X0000007B

    解决方法:开机进BIOS,更改Interface Combination,即硬盘的接口种类,由默认的RAID改成了AHCI,保存,重启,一切正常. 事件过程: 今天开机进入win7,在start wi ...

  3. SNMP 和 NetBios协议理解

      一.简单网络管理协议(SNMP,Simple Network Management Protocol)构成了互联网工程工作小组(IETF,Internet Engineering Task For ...

  4. 【boost】MFC dll中使用boost thread的问题

    项目需要,在MFC dll中使用了boost thread(<boost/thread.hpp>),LoadLibraryEx的时候出现断言错误,去掉thread库引用后断言消失. 百度g ...

  5. webstorm+nodejs+JetBrains IDE Support+chrome打造前端开发神器

    #webstorm+nodejs+JetBrains IDE Support+chrome打造前端开发神器 -- 工欲善其事 必先利其器 ##各工具介绍 `webstorm`是**JetBrains* ...

  6. 子元素过滤器nth-child解释

    jQuery中的子元素过滤器nth-child是指:选取每个父元素下的第index个子元素或者奇偶元素(index从1算起) 这里有几点要注意: 1. index 从1开始算 2. 过滤器filter ...

  7. HP ILO2 使用详细教程

    iLO是Intergrated Light-Out的缩写,是惠普特有的远程管理功能,目前最新的版本是iLO2.通过iLO2可以实现硬件级别的服务器远程管理,包括开关机.重启.服务器状态的监控.虚拟KV ...

  8. 使用bat快速创建cocos2d-x模板

    在上一篇文章中我们学习了如何使用python创建cocos2d-x 2.2工程,但是每次我们都输入一大串的命令,好烦好烦啊.参考别人的文章这里写了一个bat,如下 @echo off echo --- ...

  9. RS-232-C串口通讯协议解析(硬件接口协议)

    http://www.dz3w.com/info/interface/0075524.html http://wenku.baidu.com/view/02cc247c27284b73f24250e3 ...

  10. 关于缺省路由传递问题的探讨(上)[ip default-network、ip default-gateway等]

    指定缺省路由(last resort gateway)的指令供有3种,可以分成两类:   1.Ip default-gateway   仅在 "no ip routing" (关闭 ...