Quickstart: Create a Controller and Express Server
developFollow these steps to set up a basic RESTful API using routing-controllers and Express.
- Define a controller class using decorators like
@Controller,@Get,@Post,@Param, and@Body. - Initialize the server using
createExpressServerand pass the controllers in the configuration object. - Start the server using the standard
.listen()method.
import { createExpressServer } from 'routing-controllers';
import { Controller, Param, Body, Get, Post, Put, Delete } from 'routing-controllers';
@Controller()
export class UserController {
@Get('/users')
getAll() {
return 'This action returns all users';
}
@Get('/users/:id')
getOne(@Param('id') id: number) {
return 'This action returns user #' + id;
}
@Post('/users')
post(@Body() user: any) {
return 'Saving user...';
}
@Put('/users/:id')
put(@Param('id') id: number, @Body() user: any) {
return 'Updating a user...';
}
@Delete('/users/:id')
remove(@Param('id') id: number) {
return 'Removing user...';
}
}
const app = createExpressServer({
controllers: [UserController],
});
app.listen(3000);