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

时间: 2024-08-07 15:19:41

[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 function calls would you use to mount a middleware called logger ? Answer: app.use(logger); Default Middleware What is the only middleware that's shi

[Express] Level 3: Massaging User Data

Flexible Routes Our current route only works when the city name argument matches exactly the properties in the cities object. This is a problem. We need a way to make our code more flexible. Inside our route, call the parseCityName() function passing

[Express] Level 4: Body-parser -- Post

Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express application. npm install body-parser Require the body-parser npm module and assign it to a variable calledbodyParser. var bodyParser = require('body-parser'

[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 for the '/cities' URL path and assign it to thecitiesRoute variable. var citiesRoute = app.route('/cities'); Move the code from our previous app.get() 

[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 assign it to the router variable. var router = express.Router(); When we are done, our router will be mounted on the /cities path. With this in mind,

[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 to to create this new route. Create a new route for GET request to '/cities'. The second argument should be a callback function which takes request and

[Express] Level 4: Body-parser -- Delete

Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? Here's the link to the sendStatus function source code if you need to take a look. Answer: 404 Delete Route Create a Dynamic Route for deleting cities

[Node.js] Serve Static Files with Express

In this lesson we will find out how to serve static assets (images, css, stylesheets, etc.) with Express. We will go over writing initial boilerplate for a simple Express app, and using Express's built-in middleware to serve these assets through a we

透析Express.js

前言 最近,本屌在试用Node.js,在寻找靠谱web框架时发现了Express.js.Express.js在Node.js社区中是比较出名web框架,而它的定位是“minimal and flexible(简洁.灵活)”. 进击的Express.js 1. 底层的Http module Node有Http module,本质上,我们可以直接通过他写Web应用.Http module使用很简单: //////////////// // app.js //////////////// // 加载所