如何把render方法挂载在res上?
发布于 9 年前 作者 wp3xpp 5648 次浏览 最后一次编辑是 8 年前 来自 问答

比如 res.render = funcrion(view, data){ //TODO: }; 这个http模块的response从哪里获取?

4 回复

var res = { proto: http.ServerResponse.prototype }; exports.init = function(app){ return function expressInit(req, res, next){ if (app.enabled(‘x-powered-by’)) res.setHeader(‘X-Powered-By’, ‘Express’); req.res = res; res.req = req; req.next = next;

req.__proto__ = app.request;
res.__proto__ = app.response;

res.locals = res.locals || Object.create(null);

next();

}; }; express是利用中间件改写了req, res 看了一早上express源码 总算找到怎么弄了

var merge = require('merge-descriptors');
var http = require('http');
var EventEmitter = require('events').EventEmitter;

var res = {
  __proto__: http.ServerResponse.prototype
};

res.render = function render(){
	console.log('merge test is ok');
};

var app = {};

app.init = function init(){
	merge(app, http, false);
	merge(app, EventEmitter.prototype, false);
	app.response = { __proto__: res, app: app };
	//showFunctions(http);
	return app;
};

app.defaultConfiguration = function defaultConfiguration(){

};

var showFunctions = function (object){
	Object.getOwnPropertyNames(object).forEach(function forEachOwnPropertyName(name) {
    	console.log(name);
	})

};


var test = app.init();
test.createServer(function(req, res){
	res.__proto__ = app.response;
	res.writeHead(200, 'text/html; charset=utf8');
	res.render();
	res.end('Server is ok');
}).listen(8888);
console.log('Server is running');

这个是我解决这个问题的test

回到顶部