[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 ...
随机推荐
- python中使用多继承
python中使用多继承,会涉及到查找顺序(MRO).重复调用(钻石继承,也叫菱形继承问题)等 MRO MRO即method resolution order,用于判断子类调用的属性来自于哪个父类.在 ...
- HDU-3872 Dragon Ball 线段树+DP
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3872 题意:有n个龙珠按顺序放在一列,每个龙珠有一个type和一个权值,要求你把这n个龙珠分成k个段, ...
- 2款好用的Web在线编辑器
1.CKEditor FCKEditor 现在已经重新开发,并改名为 CKEditor. CKeditor是一个专门使用在网页上,开放源代码,高度可定制,跨平台的所见即所得文字编辑器,兼容于绝大部分的 ...
- ef6 code first
http://www.cnblogs.com/Bce-/p/3684643.html http://www.cnblogs.com/Gyoung/tag/Entity%20Framework/ htt ...
- mysql innobackupex xtrabackup 大数据量 备份 还原(转)
原文:http://blog.51yip.com/mysql/1650.html 作者:海底苍鹰 大数据量备份与还原,始终是个难点.当MYSQL超10G,用mysqldump来导出就比较慢了.在这里推 ...
- 【转】Java transient关键字
Volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同的线程总是看到某个成员变量的同一 ...
- 二十八个 HTML5 特性与技巧
1. New Doctype 你还在使用令人讨厌的难记的XHTML文档类型声明吗?<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Trans ...
- 杭电ACM减花布条
这是原题的地址 http://acm.hdu.edu.cn/showproblem.php?pid=2087 Problem Description 一块花布条,里面有些图案,另有一块直接可用的小饰条 ...
- hdu 5655 CA Loves Stick
CA Loves Stick Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others) ...
- Python字典 (dictionary)
字典dict,是Python唯一的标准mapping类型,也是内置在Python解释器中的. mapping object把一个可哈希的值(hashable value)映射到一个任意的object上 ...