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. python中类的总结

    1. 类中的方法 在类里主要有三种方法: a.普通方法:在普通方法定义的时候,需要一个对象的实例参数,从而在类中定义普通方法的时候,都必须传送一个参数self,那么这个参数也就是object b.类方 ...

  2. ansible定时任务模块和用户组模块使用

    接上篇,还是一些基础模块的使用,这里主要介绍的是系统模块的使用. 下面例子都进行过相关的实践,从而可以直接进行使用相关的命令. 3.用户模块的使用 用户模块主要用来管理用户账号和用户的属性(对远程主机 ...

  3. 黑马程序员——有关protocol的小结

    在OC程序中经常会有这样的问题就是一个类想让其他类帮自己实现某些方法,然后再将结果返回给这个类:如何让一个类要找的代理去实现自己想要的方法呢? 这样就需要有一个协议,让能遵守协议的其他类都能实现协议中 ...

  4. 前端技能汇总 Frontend Knowledge Structure

    Frontend Knowledge Structure 项目起源 还记得@jayli 的这幅前端知识结构图么. 图片的形式具有诸多的不便.缺失源图的我们,无法为此图贡献些什么,随着时间的迁移,或许有 ...

  5. 使用Java程序调用MatLab

    Java代码实现的计算难免会显得不够高效.而利用MATLAB写好相应的计算函数,然后打包成jar包供Java调用,在某些情况下会更加方便.或者有些时候会涉及到使用Java调用MatLab展现一些二维三 ...

  6. 服务器多块磁盘 ,同时磁盘类型混合(SSD+STAT+SAS)

    服务器多块磁盘 ,同时磁盘类型混合(SSD+STAT+SAS)

  7. Gridheh 垂直居中

    Gridheh 垂直居中 上下居中 each columns  set layout ColumnDefValues.Layout = tlCenter 有colResize,拖动调整列宽. 但是没有 ...

  8. sql操作table

    1.增加表字段 alter table tbsptrustquotdoc(表名)  add  chargeapplystate(字段名) char(1)(类型) default '1'(默认值) 2. ...

  9. [原创]Devexpress XtraReports 系列 7 创建Drill-Down(向下钻取)报表

    昨天发表了Devexpress XtraReports系列第六篇[原创]Devexpress XtraReports 系列 6 创建并排报表,今天我们继续. 今天的主题是创建Drill-Down报表. ...

  10. dedecms lnmp 环境搭建。备忘录非教程

    ssh链接到linux服务器,我用的centos 6.5 64位的. #设置dns,ect/reserv.conf 设置,注释掉原来的nameserver,添加nameserver=8.8.8.8访问 ...