gpt4 book ai didi

node.js - 使用 Typescript 的 Express.js 路由

转载 作者:搜寻专家 更新时间:2023-10-30 21:03:50 48 4
gpt4 key购买 nike

我想使用 Express.js使用 Typescript 来指定代码更加模块化/面向对象。

我想通过实现 IRoute 接口(interface)然后将新的 Route 添加到 app.use() 来实现 Route/Controller。

我面临的问题是每个操作(get、post、put、delete)本身都返回 IRoute 接口(interface),我不确定要返回什么。回来 return <IRoute> this;在操作中不起作用。

typescript 编译器响应以下错误消息:

Class MessurmentsController incorrectly implements interface IRoute. Types of property all are incomatible. Type (req: Request, res: Response, next: Function) => void is not assignable to type (...handler: RequestHandler[]): IRoute. Types of parameters req and handler are incomatible. Type Request is not assignable to type RequestHandler.

/// <reference path="../../../typings/tsd.d.ts" />

import {IRoute, Request,Response} from 'express';


export class MeasurementsController implements IRoute {
path: string;
stack: any;

constructor(){
this.path = "/api/measurements"
}


all(req: Request, res: Response, next: Function){
res.send('');
//return <IRoute> this;
}

get(req: Request, res: Response, next: Function){
res.send('');
}

post(req: Request, res: Response, next: Function){
res.send('');
}

put(req: Request, res: Response, next: Function){
res.send('');
}

delete(req: Request, res: Response, next: Function){
res.send('');
}
patch(req: Request, res: Response, next: Function){
res.send('');
}
options(req: Request, res: Response, next: Function){
res.send('');
}
head(req: Request, res: Response, next: Function){
res.send('');
}
}

d.ts中的Route定义为

    module e {
interface IRoute {
path: string;
stack: any;
all(...handler: RequestHandler[]): IRoute;
get(...handler: RequestHandler[]): IRoute;
post(...handler: RequestHandler[]): IRoute;
put(...handler: RequestHandler[]): IRoute;
delete(...handler: RequestHandler[]): IRoute;
patch(...handler: RequestHandler[]): IRoute;
options(...handler: RequestHandler[]): IRoute;
head(...handler: RequestHandler[]): IRoute;
}

知道我需要在操作中返回什么才能使它正常工作吗?

最佳答案

终于有了解决办法:

路由 Controller 允许使用方法创建 Controller 类作为处理请求的操作。您可以将路由 Controller 与 express.js 或 koa.js 一起使用。 https://github.com/pleerock/routing-controllers

关于node.js - 使用 Typescript 的 Express.js 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678496/

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