[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?

[Express] Level 2: Middleware -- 2的更多相关文章
- [Express] Level 2: Middleware -- 1
Mounting Middleware Given an application instance is set to the app variable, which of the following ...
- [Express] Level 4: Body-parser -- Post
Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express applic ...
- [Express] Level 3: Massaging User Data
Flexible Routes Our current route only works when the city name argument matches exactly the propert ...
- [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 ...
- [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 ...
- [Express] Level 4: Body-parser -- Delete
Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...
- [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 ...
- [Express] Level 1: First Step
Installing Express Let's start building our new Express application by installing Express. Type the ...
- 透析Express.js
前言 最近,本屌在试用Node.js,在寻找靠谱web框架时发现了Express.js.Express.js在Node.js社区中是比较出名web框架,而它的定位是“minimal and flexi ...
随机推荐
- flappy pig小游戏源码分析(1)——主程序初探
闲逛github发现一个javascript原生实现的小游戏,源码写的很清晰,适合想提高水平的同学观摩学习.读通源码后,我决定写一系列的博客来分析源码,从整体架构到具体实现细节来帮助一些想提高水平的朋 ...
- 关于在 mac上配置pytesseract的相关问题
因为踩了两个小时坑 特别是在配置依赖tesseract-ORC识别库时候的问题 特别麻烦 一定要用brewhome 一定要用brewhome 一定要用brewhome 重要的事情说三遍. 刚开始我在网 ...
- 40 个顶级 jQuery 图片、内容滑块和幻灯片(转)
在这个快速发展的网络世界中,我们使用图片.内容滑块和幻灯片来给网站实现良好.有吸引力的外观.你可以吸引浏览者借助图像滑块让网站更加具有活力.使用 JavaScript 可以轻松实现轻量级的图片和内容滑 ...
- DataGrid参数
1.3.2 data-options="singleSelect:true,collapsible:false,url:'/datagrid/getbasic'" 参数 类型 ...
- Spark RDD概念学习系列之RDD的创建(六)
RDD的创建 两种方式来创建RDD: 1)由一个已经存在的Scala集合创建 2)由外部存储系统的数据集创建,包括本地文件系统,还有所有Hadoop支持的数据集,比如HDFS.Cassandra.H ...
- 服务框架Dubbo(转)
add by zhj:该开源项目已经停止更新了,不过倒是可以学学该软件的架构设计 原文:http://www.oschina.net/p/dubbo Dubbo 是阿里巴巴公司开源的一个高性能优秀的服 ...
- 简单版问卷调查系统(Asp.Net+SqlServer2008)
1.系统主要涉及以下几个表 问卷项目表(Q_Naire) 问卷题目表(Q_Problem) 题目类型表(Q_ProblmeType) 题目选项表(Q_Options) 调查结果表(Q_Answer) ...
- WinHTTP Web Proxy Auto-Discovery Service
下面是网上搜集的,个人没有做测试,----------------------------- WinHTTP Web Proxy Auto-Discovery Service 服务成功发送一个 开始 ...
- HDU 5821 Ball (排序)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5821 有n个盒子,每个盒子最多装一个球. 现在进行m次操作,每次操作可以将l到r之间盒子的球任意交换. ...
- HDU 5707 Combine String (DP,LCS变形)
题意:给定三个字符串,问你第三个是不是由第一个和第二个组成的. 析:当时比赛是没有做出来啊...一直WA,就是没有判断长度,第一个和第二个和是不是和第三个一样,这个忘记... 我们用d[i][j]表示 ...