Sau đây chúng ta sẽ tiến hành thêm route cho ứng dụng và sẽ xuất ra màn hình dòng chữ Hello World nhé.
Tạo file routes.ts trong thư mục src của bạn với nội dung như sau:
import * as express from "express";
export default function routes(app: express.Application) {
}
Trong app.ts mà chúng ta đã viết ở bài trước chúng ta sẽ:
Import function route bằng cách:
import routes from './routes';
Tiếp theo, trong constructor() chúng ta sẽ thêm dòng sau:
routes(this.app);
Lúc này constructor của app.ts sẽ trông như sau:
constructor() {
this.app = express();
this.config();
routes(this.app);
}
Quay lại file route.ts thêm code sau vào trong function:
app.get('/hello-world', (req, res) => {
res.send('Hello World');
});
Phân tích 1 chút nhé:
- .get: đây là phương thức mà request gửi lên để route thực thi
- /hello-world: là đường dẫn mà chúng ta khai báo để có thể truy cập
- req, res: dựa vào 2 tham số này của callback, chúng ta có thể nhận các thông tin của và thao tác với request thông qua req (request). Tương tự là với res (response).
Ra trình duyệt và truy cập vào đường dẫn sau nhé: http://localhost:8080/hello-world
Nếu xuất hiện như sau thì có nghĩa là bạn đã thành công rồi đó.
Thay vì cho trực tiếp callback để chạy trong route như bên trên thì chúng ta sẽ tạo ra các controller.
Trong thư mục src tạo thư mục controllers, nơi đây sẽ chứa các controller của bạn trong tương lai.
Trong thư mục controllers đã tạo ở trên, tạo file HomeController.ts với nội dung sau:
import {Request, Response} from 'express';
class HomeController {
public helloWorld(req: Request, res: Response) {
res.send('Hello World');
}
}
export default new HomeController();
Lúc này cấu trúc thư mục của bạn sẽ trông như sau nhé:
Ra trình duyệt chạy thử nhé. Nếu vẫn như bên trên thì là được rồi đó:
import {Request, Response} from 'express';
class PostController {
public getPosts(req: Request, res: Response) {
res.send('Get all posts');
}
public addNewPost(req: Request, res: Response) {
res.send('Add new post');
}
public getPostById(req: Request, res: Response) {
res.send('Get post id: ' + req.params.id);
}
public updatePost(req: Request, res: Response) {
res.send('Update post id: ' + req.params.id);
}
public deletePost(req: Request, res: Response) {
res.send('Delete post id: ' + req.params.id);
}
}
export default new PostController();
app.route('/posts')
.get(PostController.getPosts)
.post(PostController.addNewPost);
app.route('/posts/:id')
.get(PostController.getPostById)
.put(PostController.updatePost)
.delete(PostController.deletePost);
Dùng POSTMAN để test thử các link nhé:
http://localhost:8080/posts - GET
http://localhost:8080/posts - POST
http://localhost:8080/posts/1 - GET
http://localhost:8080/posts/1 - PUT
http://localhost:8080/posts/1 - DELETE