[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 ...
随机推荐
- PermGen space Eclipse 终极解决方案
1.选中项目右键 run or debug configurations... 2.在 VM arguments 加入 -Xms128m -Xmx512m -XX:PermSize=64M -XX: ...
- 基于select模型的udp客户端实现超时机制
参考:http://www.cnblogs.com/chenshuyi/p/3539949.html 多路选择I/O — select模型 其思想在于使用一个集合,该集合中包含需要进行读写的fd,通过 ...
- 20+非常棒的Photoshop卡通设计教程
现在把一个人的脸变成卡通图案再用它来当头像这种现象使非常常见的,同样的卡通插图可以用于多种渠道的设计.网上有很多公司都会创立一种吉祥物并把它应用到市场营销中.因为有了类似于photoshop这样强大的 ...
- 关于dom节点绑定滑动事件导致浏览器上下滑动失效解决方案--黄丕巧
1.移动端开发往往需要添加一下自定义的左右滑动事件,但是添加了左右滑动事件之后就要阻止浏览器大默认事件,否则dom节点的滑动事件和浏览器本身的滑动会出现冲突,导致滑动的时候会出现消失瞬间再出现的效果 ...
- ajax 留言板
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- jszs 枚举算法
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- openstack kilo 流量
- log4j:ERROR LogMananger.repositorySelector was null likely due to error in class reloading, using NOPLoggerRepository.
The reason for the error is a new listener in Tomcat 6.0.24. You can fix this error by adding this l ...
- excel分组求和
=SUMPRODUCT((C2:C99=F2)*(B2:B99)) 说明: C2:C99=F2 找到C2到C99之间的等于F2的值 如果有多个判断条件,采用*来管理 B2:B99 求和
- 安装php5.5
安装php5.5 ./configure --prefix=/usr/local/php5.5.14/ --with-apxs2=/usr/local/apache2.2.27/bin/apxs -- ...