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.

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

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.

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

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.

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

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.

  1. next();
  1. module.exports = function (request, response, next) {
  2. var startTime = +new Date();
  3. var stream = process.stdout;
  4. var duration = null;
  5.  
  6. response.on('finish', function () {
  7. duration = +new Date() - startTime;
  8. var message = "This request took "+duration+" ms";
  9. stream.write(message);
  10. });
  11.  
  12. next();
  13. };

Add Logging Middleware

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

  1. var express = require('express');
  2. var app = express();
  3.  
  4. var logger = require('./logger');
  5.  
  6. //TODO: mount middleware
  7.  
  8. app.listen(3000);

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

Answer:

  1. 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.

  1. module.exports = function(request, response, next){
  2.  
  3. };

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.

  1. module.exports = function(request, response, next){
  2. if(request.method == "GET"){
  3. next();
  4. }
  5. };

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

  1. module.exports = function(request, response, next){
  2. if(request.method == "GET"){
  3. next();
  4. }else{
  5. response.end('Method is not allowed');
  6. }
  7. };

Buildings

  1. var express = require('express');
  2. var app = express();
  3.  
  4. app.use(function(request, response, next){
  5. if (request.path === "/cities"){
  6. next();
  7. } else {
  8. response.status(404).json("Path requested does not exist");
  9. }
  10. });
  11.  
  12. app.get('/cities', function(request, response){
  13. var cities = ['Caspiana', 'Indigo', 'Paradise'];
  14. response.json(cities);
  15. });
  1. 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. MapReduce阅读

    1.mongodb权威指南6.4章 2.百科:http://baike.baidu.com/link?url=fl9FwgNq7gtFLwJ-GuKsJ25Uk-wnhgDjEwkKd8-5hoIkh ...

  2. 企业网管软件实战之SolarWinds LANsurveyor

    SolarWinds LANsurveyor是一款比较容易掌握的网络管理软件,他能自动探索你的LAN或WAN,并生成全面的,易于浏览的集成了OSI 2层和 3层 拓扑数据的网络图表.其主要功能有: 1 ...

  3. shell脚本操作mysql库

    shell脚本操作mysql数据库-e参数执行各种sql(指定到处编码--default-character-set=utf8 -s,去掉第一行的字段名称信息-N) 2011-05-11 18:18: ...

  4. Operation not applicable

    ClientDataSet.DataSetProvider1 Operation not applicable ClientDataSet1->Open(); 解决办法 1.update new ...

  5. VS2010在C#头文件添加文件注释的方法(转)

    步骤: 1.VS2010 中找到(安装盘符以C盘为例)C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplatesCa ...

  6. hdu 2899 Strange fuction

    http://acm.hdu.edu.cn/showproblem.php?pid=2899 Strange fuction Time Limit: 2000/1000 MS (Java/Others ...

  7. 帮你选处理器:CPU T9500-p9500-T9400-T9300-p8700对比分析!

    许多人对处理器是P和T开头含混不清,不甚了解,也怪英特尔的处理器型号实在是太过复杂.这需要具体型号来看的.让我们先来看看英特尔的官方解释吧 T: Mobile Highly Performance-- ...

  8. Android SDK Manager更新不了的解决办法

    android SDK Manager更新不了,出现错误提示:"Failed to fetch URL..."! 可以用以下办法解决: 使用SDK Manager更新时出现问题 F ...

  9. visualC/C++连接MySql数据库

    vs连接数据库其实就是将mysql数据库.h头文件接口.lib链接文件和dll执行文件加入到项目中.下面是配置如何加入. 转于http://www.cnblogs.com/justinzhang/ar ...

  10. QA技能必备

    一 常用Linux命令 二 自动化工具