2014-10-13 2 views
1

node.js 요청 객체를 확장하고 사용자 정의 메소드 및 특성을 추가하려면 어떻게합니까? URL과 같은 것이 필요할 것이므로 노드의 요청에서 this에 액세스 할 수 있어야합니다.nodejs 요청 객체를 확장하십시오.

답변

5

http.createServer 콜백에 전달 된 요청 개체는 http.IncomingMessage 개체입니다. 요청 오브젝트를 보강하려면 http.IncomingMessage.prototype에 메소드를 추가 할 수 있습니다.

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

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

또 다른 방법, 즉 아무튼 :

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']; 
    } 
} 

을, 당신은 위임을 사용할 수 있습니다 오브젝트를 늘리는 작업은 request 오브젝트를 사용하는 것입니다.

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

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

이 기술은 노드 객체를 둘러싸 기 위해 koa에 많이 사용됩니다.

+0

좋습니다. 속성과 메서드가있는 사용자 정의 빌드 객체가 있으면 IncomingMessage에 병합 할 수 있습니까? – sandelius

+0

정말 대단합니다. 어떤 방법이 선호됩니까? – sandelius

+0

한 가지 방법은 모든 메소드를 반복하여'request' 객체에 추가하는 것입니다. 'for (객체의 var 키) {req [키] = 객체 [키]; }'. 'this'는'request' 객체를 참조 할 것입니다. –

관련 문제