我正在 Express JS 周围创建一个抽象层,并遇到了问题。考虑下面的代码 (见底部),当调用 registerRoute 并触发以下行时:
我遇到了这个错误:
expressFnc(route, (req: any, res: any, next: any) => dummy(req, res, next));
我遇到了这个错误:
在这个上下文中,我认为“this”是指ExpressJS(lib/application.js:479:10)。无法读取未定义的 'lazyrouter' 属性
const express = require("express");
export class ExpressHttpHost implements IHttpHost {
private host: any = express();
private contentResolver?: ContentResolver;
public configure(contentResolver: ContentResolver): void {
this.contentResolver = contentResolver;
}
public registerRoute(
route: string,
verb: HttpVerb,
handler: (request: HttpRequest) => HttpResponse,
): void {
switch (verb) {
case HttpVerb.Get:
this.createDummyRequest(this.host.get, route, handler);
break;
case HttpVerb.Delete:
this.createDummyRequest(this.host.delete, route, handler);
break;
case HttpVerb.Options:
this.createDummyRequest(this.host.options, route, handler);
break;
case HttpVerb.Patch:
this.createDummyRequest(this.host.patch, route, handler);
break;
case HttpVerb.Post:
this.createDummyRequest(this.host.post, route, handler);
break;
case HttpVerb.Put:
this.createDummyRequest(this.host.put, route, handler);
break;
case HttpVerb.All:
this.createDummyRequest(this.host.get, route, handler);
this.createDummyRequest(this.host.delete, route, handler);
this.createDummyRequest(this.host.options, route, handler);
this.createDummyRequest(this.host.patch, route, handler);
this.createDummyRequest(this.host.post, route, handler);
this.createDummyRequest(this.host.put, route, handler);
break;
default:
throw new Error("Verb is not supported.");
}
}
public start(options: IHttpHostOptions): void {
this.host.listen(options.port ? options.port : 80);
}
private createHttpRequest(expressReq: any): HttpRequest {
return new HttpRequest(
expressReq.headers,
expressReq.params,
expressReq.body,
);
}
private createDummyRequest(expressFnc: any, route: string, handler: (request: HttpRequest) => HttpResponse): void {
const dummy = (expressReq: any, expressRes: any, next: any) => {
const httpRequest = this.createHttpRequest(expressReq);
const response = handler(httpRequest);
const responseStatus = response.status();
const responseMimeType = response.mimeType();
const responseContent = response.content(this.contentResolver);
expressRes.set("Content-Type", responseMimeType);
expressRes.status(responseStatus);
expressRes.send(responseContent);
next();
};
expressFnc(route, (req: any, res: any, next: any) => dummy(req, res, next));
}
}
app.get('/api/route/:param', undefined)
,我也会遇到这个错误。 - prototype