Skip to content

Instantly share code, notes, and snippets.

@nguyentien98
Last active November 21, 2018 08:41
Show Gist options
  • Save nguyentien98/260bfc96799a1db1a624e0a50224bb5f to your computer and use it in GitHub Desktop.
Save nguyentien98/260bfc96799a1db1a624e0a50224bb5f to your computer and use it in GitHub Desktop.

Lời mở đầu

Thêm route và Hello World huyền thoại

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é.

Bước 1: Tạo file route

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) {
}

Bước 2: Import route vào app

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);
}

Bước 3: Hello World nào

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).

Bước 4: Chạy thử

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 đó.

Dùng controller

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.

Bước 1: Tạo folder

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.

Bước 2: Tạo file controller

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 đó:

Tạo CRUD controller

Bước 1: Trong thư mục src/controllers các bạn tạo file PostController.ts với nội dung như sau:

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();

Bước 2: Trong file routes.ts thêm các dòng sau vào trong route():

app.route('/posts')
    .get(PostController.getPosts)
    .post(PostController.addNewPost);

app.route('/posts/:id')
    .get(PostController.getPostById)
    .put(PostController.updatePost)
    .delete(PostController.deletePost);

Bước 3: Test thử:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment