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. 备份数据库SQL Server 2008下实测

    下面的存储过程适用: 1.一次想备份多个数据库. 2.只需要一步操作,在有存储过程的条件下. 3.可以根据自己的需要修改存储过程. /*----------------------------- De ...

  2. MySQL安装(图文详解)

    下面的是MySQL安装的图解,用的可执行文件安装的,详细说明了一下!打开下载的mysql安装文件mysql-5.0.27-win32.zip,双击解压缩,运行“setup.exe”,出现如下界面 my ...

  3. 黑马程序员——Objective-c特性

    1. 继承  Objective-c不支持多继承. Super 关键字:调用该类的父类: 超类:父类的另一种说法. 2.自定义NSLog()输出: 在类中添加description方法就可以自定义NS ...

  4. 在VS2103环境中集成Doxygen工具

    自己已将学习了两三次了吧,差不多这次该总结一下: Doxygen是一种开源跨平台的,以类似JavaDoc风格描述的文档系统,完全支持C.C++.Java.Objective-C和IDL语言,部分支持P ...

  5. Warning: $HADOOP_HOME is deprecated.解决方法

    方式1(不推荐):注释hadoop-config.sh中的 if [ "$HADOOP_HOME_WARN_SUPPRESS" = "" ] && ...

  6. onAttachedToWindow()在整个Activity生命周期的位置及使用

    onAttachedToWindow在整个Activity的生命周期中占据什么位置? 为什么要在onAttachedToWindow中修改窗口尺寸? 一.onAttachedToWindow在Acti ...

  7. mysql基础知识(5)--视图

    视图 单词:view 什么是视图: 视图可以看作是一个“临时存储的数据所构成的表”(非真实表),其实本质上只是一个select语句.只是将该select语句(通常比较复杂)进行一个“包装”,并设定了一 ...

  8. DP练习(概率,树状,状压)

    http://vjudge.net/contest/view.action?cid=51211#overview 花了好长时间了,终于把这个专题做了绝大部分了 A:HDU 3853 最简单的概率DP求 ...

  9. oracle 空值与 null

    Oracle中的空字符串基本上是被当成空NULL来处理的,我们可以从下面的得到印证. select nvl('','NULL') from dual          返回 'NULL' select ...

  10. 传统的Ado.net 参数设置:params SqlParameter[] commandParameters

    C#代码  ExecuteReader(string connectionString, CommandType commandType, string commandText, params Sql ...