[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 ...
随机推荐
- 【Java多线程】两种基本实现框架
Java多线程学习1——两种基本实现框架 一.前言 当一个Java程序启动的时候,一个线程就立刻启动,改程序通常也被我们称作程序的主线程.其他所有的子线程都是由主线程产生的.主线程是程序开始就执行的, ...
- ansible网络模块安装httplib2
ansible网络模块安装httplib2 在进行使用ansible的网络模块的时候,需要安装httplib2模块 下载地址: https://pypi.python.org/pypi?%3Aacti ...
- 数往知来JavaScript_DOM<十>
一.DOM 1.onclick事件 表示点击 一般用在-->跳转 a标签,希望点击的时候不去跳转,而是做别的事情,并在里面返回一个false <a href="http:// ...
- public static void main(String arg[])
该语句定义了main方法. main方法是程序执行的入口,所有的java程序都必须具备一个main()方法,而且必须按照如上的格式来定义. 不具有main方法的类可以编译,但不能执行.因为它没有m ...
- 第三次阅读赵炯博士的《linux内核代码完全注释》:序
这是我第三次阅读linux内核代码完全注释了,当然前两次也没有读完,第一次读到第五章,第二次第七章. 所以说,赵炯博士对我最大的帮助时介绍了intel386的结构,以及内核编程的方法. 至于真正的内核 ...
- Github在windows7环境下使用入门
1.下载并安装 下载和安装一般都没什么问题,网上的链接一大堆,不过还是在此给一个安装的地址和安装的参考吧. 当然,安装完成后要保证git能使用,必须配置github 2.配置github 首先是要创建 ...
- [转]天龙八部的BillingServer
从字面上看,Billing是计费的,应该处理玩家在线时间或者包月之类.但是天龙八部是免费游戏,不需要算时间来计费.从代码中看,BillingServer也比较简单,它有一个连接到Web服务器,并监听一 ...
- BFS寻路算法的实现
关于BFS的相关知识由于水平有限就不多说了,感兴趣的可以自己去wiki或者其他地方查阅资料. 这里大概说一下BFS寻路的思路,或者个人对BFS的理解: 大家知道Astar的一个显著特点是带有启发函数, ...
- SQL 脚本
1.USE语句 USE语句用于设置当前数据库,如果没有USE语句,那么就由执行脚本的任何用户来确定执行脚本时当前数据库是正确的.如果只是一个通用脚本,那么省去USE语句实际上可能更有益.通常,如果在脚 ...
- 存量数据处理结果查询.txt
请求报文:<?xml version="1.0" encoding="UTF-8"?><PDL><PDL-Head>< ...