[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 ...
随机推荐
- DHCP工作过程详解
DHCP动态主机配置协议的作用我想作为网管的兄弟们都应该知道了,这里我就不多废话了,今天我要谈的是DHCP的工作过程,了解了工作过程,要排除故障就容易了. 一.DHCP客户机初始化: 1. 寻找D ...
- 数往知来 三层架构 <十四>
三层架构_1 一.三层 就是把程序的各个部分都分离,尽量的底耦合,做到分工明确.责任明确 第一层:Dal 数据访问层 第二层 :Bll 业务逻辑判断层 第三层: UI 界面显示层 比如说数据 ...
- kali 安装完成后,无法进入界面
vmware 下安装 kali-1.9 ,安装完成后,无法进入界面,提示: 系统出错且无法恢复,请联系管理员 解决办法如下: 在新建虚拟机的时候,选择客户端系统:linux Debian 7. 因 ...
- 第三次阅读赵炯博士的《linux内核代码完全注释》:序
这是我第三次阅读linux内核代码完全注释了,当然前两次也没有读完,第一次读到第五章,第二次第七章. 所以说,赵炯博士对我最大的帮助时介绍了intel386的结构,以及内核编程的方法. 至于真正的内核 ...
- 【Python学习笔记】with语句与上下文管理器
with语句 上下文管理器 contextlib模块 参考引用 with语句 with语句时在Python2.6中出现的新语句.在Python2.6以前,要正确的处理涉及到异常的资源管理时,需要使用t ...
- AC多模式匹配算法
建议:学习ac算法最好的途径是看论文pdf_Efficient_String_Matching_An_Aid_to_Biblio 一.一般的搜索算法 keyword: { he, she, his, ...
- 【CLR】奇妙的String
- 一.背景 1. 以下代码的HashCode是否相同,它们是否是同个对象: var A = "ab" + "c"; var B = "abc&quo ...
- NServiceBus-日志
默认的日志 NServiceBus一些有限,固执己见,内置的日志记录. 默认的日��行为如下: 控制台 所有 Info(及以上)消息将被输送到当前的控制台. 错误将会写 ConsoleColor.Re ...
- js_sl 分享
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- 在WP8上搭建cocos2d-x开发环境
在WP8上搭建cocos2d-x开发环境 转自:https://github.com/koowolf/cocos-docs/blob/master/manual/framework/native/in ...