扩展nodejs请求对象

时间:2014-10-13 09:53:51

标签: node.js

如何扩展node.js请求对象并向其添加自定义方法和属性?我需要能够从节点的请求中访问this,因为我需要网址等。

2 个答案:

答案 0 :(得分:6)

传递给http.createServer回调的请求对象是http.IncomingMessage对象。要扩充请求对象,可以将方法添加到http.IncomingMessage.prototype

var http = require('http');

http.IncomingMessage.prototype.userAgent = function () {
  return this.headers['user-agent'];
}

添加访问者属性:

Object.defineProperty(http.IncomingMessage.prototype, 'userAgent', {
  get: function () {
    return this.headers['user-agent'];
  }
}

如果现有对象的构造函数体中定义了其方法,则可以使用delegation:

function AugmentedRequest() { 
  this.userAgent = function () {}
}

AugmentedRequest.call(request); //request now has a userAgent method

另一种不涉及扩充request对象的方法是使用合成。

var extendedRequest = {
  get userAgent() {
    this.request.headers['user-agent'];
  }
}

createServerCallback(function (req, res) {
  var request = Object.create(extendedRequest);
  request.request = req;
});

koa中大量使用此技术来包装Node对象。

答案 1 :(得分:0)

您可以将自己的类传递给 createServer 函数。

const {createServer, IncomingMessage, ServerResponse} = require('http')

// extend the default classes
class CustomReponse extends ServerResponse {
  json(data) {
    this.setHeader("Content-Type", "application/json");
    this.end(JSON.stringify(data))
  }
  status(code) {
    this.statusCode = code
    return this
  }
}

class CustomRequest extends IncomingMessage {
   // extend me too
}

// and use as server options
const serverOptions = {
  IncomingMessage: CustomRequest,
  ServerResponse: CustomReponse,
}

createServer(serverOptions, (req, res) => {
  // example usage
  res.status(404).json({ 
    error: 'not found', 
    message: 'the requested resource does not exists' 
  })
}).listen(3000)