[Tạo server Node API : Vue.js + Express + MySQL] Quick Start - Part 1 : Hiểu về trao đổi thông tin giữa Front-end và Back-end bằng Vue.js + Express


Trước khi vào bài…

Series này không chỉ giới thiệu quá trình xử lý Front-end bằng Vue.js mà còn có quá trình liên kết data thông qua API bằng cách sử dụng Express và MySQL. Tôi đã xây dựng sao cho người mới nhập môn Vue.js cũng có thể dễ dàng hiểu được, và đã ghi lại ở bên dưới một số tài liệu tham khảo trong quá trình này.

Series được chia làm ba phần.

Part1. Hiểu về trao đổi thông tin giữa Front-end và Back-end bằng Vue.js + Express
Part2. Liên kết DB bằng Express + MySQL
Part3. Mix All — Phát triển chức năng Log In / Đăng ký thành viên

Đây là Part1, một ví dụ đơn giản giúp bạn có thể hiểu được Front-end và Back-end trao đổi data như thế nào bằng Vue.js + Express.


Step1. Setting môi trường phát triển Front-end (Vue.js)

Ta lập một folder để thực hành. Trong bài này tôi sẽ gọi là ‘movie’.

Thực hiện lệnh sau trong folder movie và setting môi trường project Vue Cli 3.x

npm install -g yarn 
npm install -g @vue/cli 
vue create frontend // create frontend folder cd frontend
npm run serve //Server running

Nếu truy cập vào locahost:8080, bạn có thể check được màn hình như sau.

Màn hình được hiện đầu tiên của Vue Cli 3.x

Step2. Setting môi trường phát triển Back-end (Express)

Quá trình này cũng diễn ra trong folder 'movie'. Chạy lệnh sau để cài đặt framework express.

npm install -g express-generator
express --view=pug backend // create backend folder cd backend
npm install 
npm start // Server running

Nếu truy cập vào locahost:3000, bạn có thể check được màn hình như sau

Màn hình được hiện đầu tiên của Express

Step3. Liên kết với Back-end

Di chuyển đến folder movie/frontend, và sau khi tạo vue.config.js thì nhập như sau.

module.exports = {
    devServer: { ① Set where to process when an api request is made
        proxy: { 
            '/api': { 
                target: 'http://localhost:3000/api',
                changeOrigin: true, 
                pathRewrite: { 
                    '^/api': ''
                } 
            } 
        } 
    },
    outputDir: '../backend/public', ② Specify the location of the distribution file
}

Sau khi chỉ định vị trí của file publish như trên, nếu chạy npm run build trong folder frontend với trạng thái Express server kết thúc, có thể thấy cấu trúc folder backend/public được thay đổi như sau..

Thay đổi cấu trúc folder khi publish bình thường

Sau đó nếu chạy server Express sẽ thấy page localhost:3000 cũng đã thay đổi giống với bên Front-end.


Step4. Chuẩn bị data sẽ gửi từ Back-end đến Front-end

Chuẩn bị data như sau bằng tên movies.json dưới folder backend. Tôi đã lấy data từ Naver movie.

[
    {
        "id": 1,
        "name": "helminth",
        "rate": "54.80%",
        "director": "Bong Joon-ho",
        "actors": "Song Kang-ho (Kitak), Lee Sun-gyun (President), Jo Yeo-jung (Yeonkyo)",
        "time": "131 minutes",
        "synopsis": "I didn't want to bother you.
It's a long way to live as a rural village, but a good family (Song Kang-ho).
The high-school tutoring place that my eldest son Ki-woo (Choi Woo-sik) linked to his best-known college student
It is the hope of a fixed income that has sprouted.
With the help and anticipation of the whole family, she goes to the home of Dr. Seon-gyun Lee.
When we arrive at the residence of Dr. Chang, CEO of global IT company
Young and beautiful wife's alma mater (Jo Yeo-jung) greets.", "poster": "https://movie-phinf.pstatic.net/20190528_36/1559024198386YVTEw_JPEG/movie_image.jpg?type=f125" }, { "id": 2, "name": "Aladdin", "rate": "21.10%", "director": "Guy Rich", "actors": "Mena Masud (Aladdin), Will Smith (Genie), Naomi Scott (Jasmine), etc.", "time": "128 minutes", "synopsis": "The age of the mysterious Agrava kingdom in the far desert.
The little thief “Aladdin” went out to find a magic lamp at the request of the wizard “Jaffa”
You meet Jini, who gives her three wishes,
While trying to win the heart of Princess Jasmine, she gets caught up in an adventure she never thought she could.", "poster": "https://movie-phinf.pstatic.net/20190524_104/1558663170174Q2mmw_JPEG/movie_image.jpg?type=f125" }, ... syncopation]

Bây giờ thiết lập router. Sau khi tạo movies.js dưới backend/routes/, nhập như sau.

var express = require('express');
var router = express.Router();
var movies = require('../movies.json');router.get('/', function (req, res, next) {
    res.send(movies)
});// Code for the movie detail page
router.get('/:id', function (req, res, next) {
    var id = parseInt(req.params.id, 10)
    var movie = movies.filter(function (movie) {
        return movie.id === id
    });
    res.send(movie)
});module.exports = router;

Trong backend/app.js thêm nội dung sau. Khi bên Front-end gửi yêu cầu /api/movies, code trên sẽ xử lý data thông qua router đã thiết lập.

…
var moviesRouter = require('./routes/movies');
…
app.use('/api/movies', moviesRouter);

Step5. Tạo màn hình sẽ hiển thị ở Front

Di chuyển đến frontend/src/component rồi tạo MovieIndexPage.vue và nhập như sau.

<template>
    <div class="wrap">
        <h1>Movie reservation rankings for the last week of May</h1>
        <ul class="movies">
            <li v-for="movie in movies" class="item">
                <span class="rank">{{movie.id}}</span>
                <router-link :to="{ name: 'show', params: { id: movie.id }}">
                    <img v-bind:src="movie.poster" class="poster">
                </router-link>
                <div class="detail">
                    <strong class="tit">{{movie.name}}</strong>
                    <span class="rate">Advance rate <span class="num">{{movie.rate}}</span></span>
                    <router-link :to="{ name: 'show', params: { id: movie.id }}" class="link">View details</router-link>
                </div>
            </li>
        </ul>
    </div>
</template>
<script>
    export default {
        created () {
            // When the component is created, it sends a request to / api / movies.
            this.$http.get('/api/movies')
            .then((response) => {
                this.movies = response.data
            })
        },
        data () {
            return {
                movies: []
            }
        }
    }
</script>

Tạo MovieShowPage.vue làm page chi tiết rồi nhập như sau.

<template>
    <div class="detail">
        <h1>{{movie.name}}</h1>
        <img v-bind:src="movie.poster" class="poster">
        <section>
            <h2>Movie Information</h2>
            <dl class="info">
                <dt>director</dt>
                <dd>{{movie.director}}</dd>
                <dt>Appearance</dt>
                <dd>{{movie.actors}}</dd>
                <dt>Running Time</dt>
                <dd>{{movie.time}}</dd>
            </dl>
        </section>
        <section>
            <h2>summary</h2>
            <p v-html="movie.synopsis" class="synopsis"></p>
        </section>
        <router-link :to="{ name: 'index', params: { id: movie.id }}" class="link">go back</router-link>
    </div>
</template>
<script>
    export default {
        created: function () {
            var id = this.$route.params.id;
            this.$http.get('/api/movies/${id}')
            .then((response) => {
                this.movie = response.data[0]
            })
        },
        data: function () {
            return {
                movie: {}
            }
        }
    }
</script>

Bây giờ ta sẽ thiết lập router. Thiết lập Vue router package bằng mệnh lệnh npm install vue-router --save.

fontend/src/routes/index.js Create it, and enter.

import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/components/MovieIndexPage'
import Show from '@/components/MovieShowPage'

Vue.use(Router)

export const router = new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'index',
            component: Index
        },
        {
            path: '/:id',
            name: 'show',
            component: Show
        }
    ]
})

Do router đã được tạo, nên ta thêm yếu tố <router-view> ở frontend/src/app.vue.

<template>
    <div id="app">
      <router-view></router-view>
    </div>
</template>

Chạy lệnh npm install axios --save cho trao đổi thông tin API, rồi cài đặt axios package.

Sau đó sửa frontend/src/main.js như sau.

import Vue from 'vue'
import App from './App.vue'
import {router}  from './routes/index.js'
import axios from 'axios'

Vue.config.productionTip = false
Vue.prototype.$http = axios;

new Vue({
    render: h => h(App),
    router,
}).$mount('#app')

Step6. Hoàn thiện

Chạy Vue server và check xem đã hoạt động bình thường hay chưa..

Màn hình mục lục
Màn hình chi tiết phim

Sau khi chạy build bằng lệnh npm run build, nếu có thể thấy cùng một màn hình trên localhost:3000 thì tức là thực hành thành công.

Quá trình này cho thấy data được trao đổi như thế nào giữa Front-end và Back-end. Trong Part sau, tôi sẽ giới thiệu cách xử lý data động chứ không phải tĩnh thông qua liên kết DB bằng Express + MySQL.


URL tham khảo


Thông tin series


🔍 Chúng tôi đang tìm kiếm FE Developer tài năng đồng hành cùng với Hivelab.

Comments

Popular posts from this blog

[React.js trong thực tiễn] Part3 : Tạo list gọi data sử dụng axios

[Activity] Một ngày tới thăm công ty mẹ Hivelab

[Activity] Hành trình du lịch Hàn Quốc của nhân viên Hivelab Vina