怎么在 postman 上运行这个 本地主机:3000/api/watson/get-test
它给出错误 -> TypeError: 无法读取未定义的属性“myTest”
import {Router, Request, Response, NextFunction} from 'express';
export class IbmWatsonRouter {
router: Router;
mytest: any;
/**
* Initialize the Router
*/
constructor() {
this.mytest = new Service();
this.router = Router();
this.init();
}
/**
* Get
*/
public getTest(req: Request, res: Response, next: NextFunction) {
res.send(this.mytest.getSomething());
}
/**
* POST Analyze-Text.
*/
public analyzeText(req: Request, res: Response, next: NextFunction) {
this.mytest.setSomething('aaaa');
res.send('successfully analyze text');
}
/**
* Take each handler, and attach to one of the Express.Router's
* endpoints.
*/
init() {
this.router.get('/get-test', this.getTest);
this.router.post('/analyze-text', this.analyzeText);
}
}
最佳答案
尝试将路由器、服务和 Controller 分开。此外, Controller 中的任何函数都应该是静态的。
路由器
import {Router} from 'express';
import {IbmWatsonController} from './controllers/ibmwatson';
export const router = Router();
router.get('/get-test', IbmWatsonController.getTest);
router.post('/analyze-text', IbmWatsonController.analyzeText);
Controller
import {Request, Response, NextFunction} from 'express';
import {Service} from '../services/service';
const serviceInstance = new Service();
export class IbmWatsonController {
public static getTest(req: Request, res: Response, next: NextFunction) {
res.send(serviceInstance.example);
}
public static analyzeText(req: Request, res: Response, next: NextFunction) {
serviceInstance.example = 'aaaa';
res.send('successfully analyze text');
}
}
服务
//@todo: rewrite with stateless solution
export class Service {
privat mytest = 'aaaaa';
get example(): string {
return mytest;
}
set example(val: string): string {
this.mytest = val;
}
}
关于javascript - 如何在nodejs typescript 中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44865353/