javascript - 如何在nodejs typescript 中设置变量

标签 javascript node.js express typescript

怎么在 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/

相关文章:

javascript - 使用 WebRTC 时不立即显示视频

javascript - 是否可以使用 “HERE Maps API for JavaScript” 以可接受的性能渲染邮政编码边框?

javascript - 将 jQuery 应用于 div 的每个部分

javascript - 通过GET请求只拉取对象的某些部分

node.js - 如何让express.static中间件忽略get参数?

javascript - 在缩放的 div 中设置 div 鼠标坐标

javascript - 检索导入的 Sequelize 模型

arrays - 按顺序将 XML 解析为数组

node.js - app.router 和 express.static 的 Expressjs 顺序

node.js - 路由后的 Node Express 4 中间件