gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:57:37 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com