在使用TypeScript时,处理Express控制器方法参数可以通过以下几种方式:
import { Request, Response } from 'express';
class UserController {
getUser(req: Request, res: Response): void {
const userId: string = req.params.id;
// 处理逻辑
}
}
import { Request, Response } from 'express';
interface CreateUserRequest {
name: string;
email: string;
password: string;
}
class UserController {
createUser(req: Request, res: Response): void {
const userData: CreateUserRequest = req.body;
// 处理逻辑
}
}
import { Request, Response } from 'express';
class UserController {
getUsers(req: Request, res: Response): void {
const page: number = req.query.page;
const limit: number = req.query.limit;
// 处理逻辑
}
}
import { Request, Response } from 'express';
class UserController {
getUser(req: Request, res: Response): void {
const userId: string = req.params.id;
// 处理逻辑
}
}
body-parser
)来解析请求体。例如:import { Request, Response } from 'express';
class UserController {
createUser(req: Request, res: Response): void {
const name: string = req.body.name;
const email: string = req.body.email;
const password: string = req.body.password;
// 处理逻辑
}
}
以上是处理Express控制器方法参数的几种常见方式。根据具体的业务需求和参数类型,选择合适的方式来处理参数。
领取专属 10元无门槛券
手把手带您无忧上云