Tutorial Node.js Express, MySQL dan Vue Js (Full Stack)
Tidak hanya itu,
Pada tutorial ini Anda juga akan belajar menggunakan Bulma CSS untuk style pada frontend.
Dengan demikian aplikasi menjadi lebih user friendly dengan user interface (UI) yang elegan dan responsif.
Ini bukanlah tutorial untuk pemula,
Jika Anda seorang pemula di node.js express, saya sarankan Anda terlebih dahulu mempelajari “Tutorial Express Js Untuk Pemula”.
Tutorial ini terdiri dari 3 parts: Part #1 Backend, Part #2 Frontend, dan Part #3. Testing.
Mari kita mulai.
Part #1. Backend
1.1. Buat database dan table
Buat database baru pada MySQL, Anda dapat menggunakan tools seperti SQLyog, PHPMyAdmin atau sejenisnya.
Disini saya membuat database dengan nama pos_db.
Jika Anda membuat database dengan nama yang sama itu lebih baik.
Untuk membuat database dengan MySQL, dapat dilakukan dengan mengeksekusi query berikut:
1 | CREATE DATABASE pos_db; |
Perintah SQL diatas akan membuat sebuah database dengan nama pos_db.
Selanjutnya, buat sebuah table di dalam database pos_db.
Disini saya membuat sebuah table dengan nama product.
Jika Anda membuat table dengan nama yang sama itu lebih baik.
Untuk membuat table product, dapat dilakukan dengan mengeksekusi perintah SQL berikut:
1 2 3 4 5 | CREATE TABLE product(product_id INT(11) PRIMARY KEY AUTO_INCREMENT,product_name VARCHAR(200),product_price DOUBLE)ENGINE=INNODB; |
1.2. Install Express, MySQL2, dan Cors
Buat sebuah folder di komputer Anda, disini saya beri nama “fullstack-app”.
Jika Anda membuat dengan nama yang sama, itu lebih baik.
Anda bebas membuatnya di manapun, baik di C, D, ataupun di Desktop.
Folder ini akan menjadi folder project kita nantinya.
Kemudian buka folder tersebut menggunakan kode editor, disini saya menggunakan Visual Studio Code.
Saya juga menyarankan Anda untuk menggunakan Visual Studio Code.
Anda dapat mendownload Visual Studio Code pada link berikut dan menginstallnya di komputer Anda:
https://code.visualstudio.com/
Selanjutnya, buka terminal pada Visual Studio Code pada menubar terminal.
Kemudian, buat folder “backend” di dalam folder “fullstack-app” dengan mengetikan perintah berikut pada terminal:
1 | mkdir backend |
Kemudian masuk ke folder “backend” dengan perintah berikut:
1 | cd backend |
Setelah itu, ketikan perintah berikut untuk membuat file “package.json” di dalam folder “backend”:
1 | npm init –y |
Selanjutnya, install express, mysql2, dan cors dengan mengetikan perintah berikut pada terminal:
1 | npm install express mysql2 cors |
Seperti gambar berikut:

Selanjutnya, tambahkan kode berikut pada file “package.json”:
1 | "type": "module", |
Sehingga file “package.json” terlihat menjadi seperti berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | { "name": "backend", "version": "1.0.0", "description": "", "type": "module", "main": "index.js", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "cors": "^2.8.5", "express": "^4.17.1", "mysql2": "^2.2.5" }} |
Hal ini bertujuan agar kita dapat menggunakan ES6 Module Syntax untuk export dan import module.
1.3. Struktur Aplikasi
Agar aplikasi lebih terstruktur rapi, kita akan menerapkan pola MVC (Model-View-Controllers).
Buat folder “config”, “controllers”, “models”, dan “routes” di dalam folder “backend”.
Kemudian buat file “database.js” di dalam folder “config”, buat file “product.js” di dalam folder “controllers”, buat file “productModel.js” di dalam folder “models”, buat file “routes.js” di dalam folder “routes”, dan buat file “index.js” di dalam folder “backend”.
Perhatikan gambar berikut untuk lebih jelasnya:

1.4. Connect ke Database
Buka file “database.js” pada folder “config”, kemudian ketikan kode berikut:
1 2 3 4 5 6 7 8 9 10 11 | import mysql from "mysql2"; // create the connection to databaseconst db = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'pos_db'});export default db; |
1.5. Models
Buka file “productModel.js” pada folder “models”, kemudian ketikan kode berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | // import connectionimport db from "../config/database.js";// Get All Productsexport const getProducts = (result) => { db.query("SELECT * FROM product", (err, results) => { if(err) { console.log(err); result(err, null); } else { result(null, results); } }); }// Get Single Productexport const getProductById = (id, result) => { db.query("SELECT * FROM product WHERE product_id = ?", [id], (err, results) => { if(err) { console.log(err); result(err, null); } else { result(null, results[0]); } }); }// Insert Product to Databaseexport const insertProduct = (data, result) => { db.query("INSERT INTO product SET ?", [data], (err, results) => { if(err) { console.log(err); result(err, null); } else { result(null, results); } }); }// Update Product to Databaseexport const updateProductById = (data, id, result) => { db.query("UPDATE product SET product_name = ?, product_price = ? WHERE product_id = ?", [data.product_name, data.product_price, id], (err, results) => { if(err) { console.log(err); result(err, null); } else { result(null, results); } }); }// Delete Product to Databaseexport const deleteProductById = (id, result) => { db.query("DELETE FROM product WHERE product_id = ?", [id], (err, results) => { if(err) { console.log(err); result(err, null); } else { result(null, results); } }); } |
1.6. Controllers
Buka file “product.js” pada folder “controllers”, kemudian ketikan kode berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | // Import function from Product Modelimport { getProducts, getProductById, insertProduct, updateProductById, deleteProductById } from "../models/productModel.js";// Get All Productsexport const showProducts = (req, res) => { getProducts((err, results) => { if (err){ res.send(err); }else{ res.json(results); } });}// Get Single Product export const showProductById = (req, res) => { getProductById(req.params.id, (err, results) => { if (err){ res.send(err); }else{ res.json(results); } });}// Create New Productexport const createProduct = (req, res) => { const data = req.body; insertProduct(data, (err, results) => { if (err){ res.send(err); }else{ res.json(results); } });}// Update Productexport const updateProduct = (req, res) => { const data = req.body; const id = req.params.id; updateProductById(data, id, (err, results) => { if (err){ res.send(err); }else{ res.json(results); } });}// Delete Productexport const deleteProduct = (req, res) => { const id = req.params.id; deleteProductById(id, (err, results) => { if (err){ res.send(err); }else{ res.json(results); } });} |
1.7. Routes
Buka file “routes.js” pada folder “routes”, kemudian ketikan kode berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // import expressimport express from "express";// import function from controllerimport { showProducts, showProductById, createProduct, updateProduct, deleteProduct } from "../controllers/product.js";// init express routerconst router = express.Router();// Get All Productrouter.get('/products', showProducts);// Get Single Productrouter.get('/products/:id', showProductById);// Create New Productrouter.post('/products', createProduct);// Update Productrouter.put('/products/:id', updateProduct);// Delete Productrouter.delete('/products/:id', deleteProduct);// export default routerexport default router; |
1.8. Index.js
Buka file “index.js” pada folder “backend”, kemudian ketikan kode berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // import expressimport express from "express";// import corsimport cors from "cors";// import routesimport Router from "./routes/routes.js";// init expressconst app = express();// use express jsonapp.use(express.json());// use corsapp.use(cors());// use routerapp.use(Router); |
Selanjutnya, ketikan perintah berikut pada terminal:
1 | node index |
Seperti gambar berikut:

Sampai disini Anda telah berhasil membuat backend.
Untuk memastikan backend berjalan dengan baik, Anda dapat menggunakan POSTMAN untuk melakukan pengujian.
Part #2. Frontend
2.1. Install Vue CLI
Untuk menginstall Vue CLI dapat dilakukan dengan mudah menggunakan NPM.
Buka terminal baru pada Visual Studio Code, kemudian ketikan perintah berikut untuk menginstall Vue CLI:
1 | npm install –g @vue/cli |
Perintah diatas, akan menginstal Vue CLI secara global di komputer Anda.
Untuk memastikan Vue CLI terinstall di komputer Anda, ketikan perintah berikut pada terminal:
1 | vue --version |
Seperti gambar berikut:

2.2. Create Vue Project
Jika Vue CLI telah terinstal di komputer Anda, silahkan buat project vue dengan mengetikan perintah berikut pada terminal:
1 | vue create frontend |
Jika instalasi berhasil, maka akan terdapat folder “frontend” di dalam folder “fullstack-app”.
Sehingga di dalam folder “fullstack-app” terdapat dua folder yaitu: “backend” dan “frontend” seperti gambar berikut:

Folder “backend” merupakan folder aplikasi yang dibangun sebelumnya menggunakan node.js express, sedangkan “frontend” merupakan folder aplikasi yang dibuat menggunakan vue js.
Selanjutnya, masuk kedalam folder “frontend” dengan mengetikan perintah berikut pada terminal:
1 | cd frontend |
Setelah itu, install vue-router, axios, dan bulma dengan mengetikan perintah berikut pada terminal:
1 | npm install vue-router axios bulma |
Seperti gambar berikut:

Vue-router berfungsi untuk membuat route pada aplikasi vue js, axios merupakan promise based http client untuk browser dan node.js, dan bulma merupakan framework CSS untuk mempercantik user interface (UI).
Setelah itu, untuk memastikan semuanya berjalan dengan baik, ketikan perintah berikut untuk menjalankan aplikasi vue js:
1 | npm run serve |
Seperti gambar berikut:

Buka browser Anda, kemudian kunjungi URL berikut:
Jika berjalan dengan baik, maka akan tampil seperti berikut:

2.3. Components
Buat file components “ProductList.vue”, “AddProduct.vue”, dan “EditProduct.vue” pada folder “frontend/src/components”.
Seperti gambar berikut:

Buka file “ProductList.vue”, kemudian ketikan kode berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | <template> <div> <router-link :to="{ name: 'Create' }" class="button is-success mt-5" >Add New</router-link > <table class="table is-striped is-bordered mt-2 is-fullwidth"> <thead> <tr> <th>Product Name</th> <th>Price</th> <th class="has-text-centered">Actions</th> </tr> </thead> <tbody> <tr v-for="item in items" :key="item.product_id"> <td>{{ item.product_name }}</td> <td>{{ item.product_price }}</td> <td class="has-text-centered"> <router-link :to="{ name: 'Edit', params: { id: item.product_id } }" class="button is-info is-small" >Edit</router-link > <a class="button is-danger is-small" @click="deleteProduct(item.product_id)" >Delete</a > </td> </tr> </tbody> </table> </div></template><script>// import axiosimport axios from "axios";export default { name: "ProductList", data() { return { items: [], }; }, created() { this.getProducts(); }, methods: { // Get All Products async getProducts() { try { this.items = response.data; } catch (err) { console.log(err); } }, // Delete Product async deleteProduct(id) { try { await axios.delete(`http://localhost:5000/products/${id}`); this.getProducts(); } catch (err) { console.log(err); } }, },};</script><style></style> |
Selanjutnya, buka file “AddProduct.vue”, kemudian ketikan kode berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <template> <div> <div class="field"> <label class="label">Product Name</label> <div class="control"> <input class="input" type="text" placeholder="Product Name" v-model="productName" /> </div> </div> <div class="field"> <label class="label">Price</label> <div class="control"> <input class="input" type="text" placeholder="Price" v-model="productPrice" /> </div> </div> <div class="control"> <button class="button is-success" @click="saveProduct">SAVE</button> </div> </div></template><script>// import axiosimport axios from "axios";export default { name: "AddProduct", data() { return { productName: "", productPrice: "", }; }, methods: { // Create New product async saveProduct() { try { product_name: this.productName, product_price: this.productPrice, }); this.productName = ""; this.productPrice = ""; this.$router.push("/"); } catch (err) { console.log(err); } }, },};</script><style></style> |
Selanjutnya, buka file “EditProduct.vue”, kemudian ketikan kode berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | <template> <div> <div class="field"> <label class="label">Product Name</label> <div class="control"> <input class="input" type="text" placeholder="Product Name" v-model="productName" /> </div> </div> <div class="field"> <label class="label">Price</label> <div class="control"> <input class="input" type="text" placeholder="Price" v-model="productPrice" /> </div> </div> <div class="control"> <button class="button is-success" @click="updateProduct">UPDATE</button> </div> </div></template><script>// import axiosimport axios from "axios";export default { name: "EditProduct", data() { return { productName: "", productPrice: "", }; }, created: function () { this.getProductById(); }, methods: { // Get Product By Id async getProductById() { try { const response = await axios.get( `http://localhost:5000/products/${this.$route.params.id}` ); this.productName = response.data.product_name; this.productPrice = response.data.product_price; } catch (err) { console.log(err); } }, // Update product async updateProduct() { try { await axios.put( `http://localhost:5000/products/${this.$route.params.id}`, { product_name: this.productName, product_price: this.productPrice, } ); this.productName = ""; this.productPrice = ""; this.$router.push("/"); } catch (err) { console.log(err); } }, },};</script><style></style> |
2.4. Main.js
Buka file “main.js” pada folder “frontend/src”, kemudian ubah menjadi seperti berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import Vue from 'vue'import VueRouter from 'vue-router'import App from './App.vue'import Create from './components/AddProduct.vue'import Edit from './components/EditProduct.vue'import Index from './components/ProductList.vue'Vue.use(VueRouter)Vue.config.productionTip = falseconst routes = [ { name: 'Create', path: '/create', component: Create }, { name: 'Edit', path: '/edit/:id', component: Edit }, { name: 'Index', path: '/', component: Index },];const router = new VueRouter({ mode: 'history', routes: routes })new Vue({ // init router router, render: h => h(App),}).$mount('#app') |
2.5. App.vue
Buka file “App.vue” pada folder “frontend/src”, kemudian ubah menjadi seperti berikut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <template> <div id="app" class="container is-max-desktop"> <router-view /> </div></template><script>export default { name: "App",};</script><style>/* import style bulma */@import "~bulma/css/bulma.css";</style> |
Part #3. Testing
3.1. READ
Kembali ke browser dan kunjungi URL berikut:
Jika berjalan dengan baik, maka akan tampil seperti gambar berikut:

3.2. CREATE
Klik tombol “Add New”, maka akan tampil form seperti berikut:

Masukan Product Name dan Price, kemudian klik tombol “SAVE”.
Jika insert berhasil, maka akan tampil seperti gambar berikut:

3.3. UPDATE
Untuk mengupdate data klik tombol “Edit”, maka akan tampil form seperti berikut:

Ubah Product Name atau Price, kemudian klik tombol “UPDATE”.
Jika update berhasil, maka akan tampil seperti gambar berikut:

3.4. DELETE
Untuk menghapus data klik tombol “Delete”.
Jika delete berhasil, maka data akan hilang dari list.
Kesimpulan:
Pembahasan kali ini adalah bagaimana membuat full stack aplikasi dengan backend node.js express dan frontend menggunakan vue.js.
Dengan demikian, Anda telah memiliki gambaran bagaimana membuat aplikasi web modern yang memisahkan antara backend dan frontend.
Tidak hanya itu, Anda juga telah belajar membuat frontend Single Page Application (SPA) menggunakan Vue CLI.
Jadi tunggu apalagi, Let’s Coding!
Komentar
Posting Komentar