使用Express和打字稿的RESTful服务 - 未定义Response.send()
问题描述:
出现“this”在express.Response.send()方法内未定义。有没有办法仍然发送我的路由器的成员?使用Express和打字稿的RESTful服务 - 未定义Response.send()
我-router.ts:
import { Router, Request, Response, NextFunction } from 'express';
import { MyTsObject } from "../my-ts-object";
export class MyRouter {
router: Router;
myTsObject: MyTsObject;
constructor() {
this.myTsObject = new MyTsObject();
this.router = Router();
this.init();
}
public getData(req: Request, res: Response, next: NextFunction){
res.send(JSON.stringify(this.myTsObject)); // runtime error here:
// TypeError: Cannot read property 'myTsObject' of undefined
}
init() {
this.router.get('/', this.getData);
}
}
app.ts:
import * as express from 'express';
import * as logger from 'morgan';
import * as bodyParser from 'body-parser';
import { MyRouter } from "./routes/my-router";
class App {
public express: express.Application;
constructor() {
this.express = express();
this.middleware();
this.routes();
}
private middleware(): void {
this.express.use(logger('dev'));
this.express.use(bodyParser.json());
this.express.use(bodyParser.urlencoded({ extended: false}));
}
private routes(): void {
this.express.use('/', new MyRouter().router);
}
}
export default new App().express;
index.ts:
import * as http from 'http';
import * as debug from 'debug';
import App from './app';
debug('ts-express:server');
const port = normalizePort(process.env.PORT || 3000);
App.set('port', port);
const server = http.createServer(App);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
....
参见运行时的我的router.ts文件当我在浏览器中点击网址时发生的错误。我假设在这个上下文中'this'不是指MyRouter对象。是否还有一种方法可以从send()方法中获取对myTsObject的引用?有没有更好的方法来做到这一点?
答
您可以将getData
方法的上下文绑定到MyRouter
在init
方法:
init() {
this.router.get('/', this.getData.bind(this));
}
另外,您可以通过一个匿名函数来router.get
能实现相同的事情:
init() {
this.router.get('/', (req: Request, res: Response, next: NextFunction) => this.getData(req, res, next));
}