gpt4 book ai didi

javascript - 如何在 typescript 中导出类并定义中间件

转载 作者:行者123 更新时间:2023-12-03 13:39:53 26 4
gpt4 key购买 nike

我创建了类用户,我只定义了 get 方法,但是当我在中间件中调用类并使用它时,它没有显示任何错误,但是当我运行代码时它显示找不到服务器。当我删除这条线 app.use(userRoute) 我的服务器工作。
用户.ts

import { NextFunction, Request, Response } from 'express';
import { Controller, Get, Req, Res } from 'routing-controllers'

@Controller()
class User {
@Get('/signup')

signUP(@Req() req: Request, @Res() res: Response, next: NextFunction) {
return res.render('signup')

};
}

export { User as userRoute }
应用程序.ts
const express = require('express')
const path = require('path')
const app = express()
import { userRoute } from "./routes/user";

const bodyPaser = require('body-parser')


app.use(bodyPaser.urlencoded({ extended: true }))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')


app.use(userRoute)

app.use('/', (req, res) => {

res.write('<html lang="eng">');
res.write('<head><title>Page</title><style>body{background-color: wheat; color: red; font- size: 25px; padding-left: 250px;}.d{}</style></head>')
res.write('<body><h1>It is working</h1></body>')
res.write('</html>')
return res.end()
});

app.listen('3000')
console.log('working')

最佳答案

在导出之前创建类的实例。
尝试一些像:

class User {
...
}

const userRoute = new User()
export {userRoute}

Updated based in doc of routing-controllers


根据 github该库的页面,在 express 中的使用应该是这样的:

@Controller()
export class UserController {

@Get("/users")
getAll(@Req() request: Request, @Res() response: Response) {
return response.send("Hello response!");
}

}


import "reflect-metadata";
import { useExpressServer } from "routing-controllers";

let express = require("express"); // or you can import it if you have installed typings
let app = express(); // your created express server
// app.use() // you can configure it the way you want
useExpressServer(app, { // register created express server in routing-controllers
controllers: [UserController] // and configure it the way you need (controllers, validation, etc.)
});
app.listen(3000); // run your express server

看看他们的文档

关于javascript - 如何在 typescript 中导出类并定义中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65124728/

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