Sử dụng Restful API NodeJS

Sử dụng Restful API NodeJS hướng dẫn cách gọi API trong trang web. Có thể gọi bằng hàm fetch, xmlHttpRequest, hay dùng thư viện Jquery, Axios, AngularJS, VueJS …Bài viết này hướng dẫn bạn dùng Fetch API (hàm fetch) và thư viện axios



Chuẩn bị để sử dụng restful api

Chuẩn bị để sử dụng restful apirestful API cái đã rồi mới gọi được, ở bài hướng dẫn RESTful API trong NodeJS , bạn đã thực hiện với một bộ restful API cho sách. Bây giờ bạn tạo nhanh một bộ khác (users) để phục vụ bài này nhé, cũng là dịp để ôn lại restful đã học ở bài trước.

1. Tạo database và table

  • Vào phpmyadmin, tạo 1 database tên shop (nếu  có rồi thì khỏi tạo)
  • Vào >1. Tạo database và tablesers như sau:
table-users-structure
table-users-data

3. Tạo project để thực tập

– Vẫn trong command line rồi chạy lệnh:  

express --view>3. Tạo project để thực tập

– Chuyển vào folder SuDungAPI mới tạo và chạy lệnh cài đặt các module cần thiết

npm install
npm install mysql
npm install nodemon

4. Tạo model kết nối db

– Tạo folder models trong project , tạo file models/database.js và code

var >4. Tạo model kết nối dbsql'); 
var db = mysql.createConnection({   
    host: 'localhost',     
    user: 'root',     
    password: '',     
    database: 'shop' 
});  
db.connect(function(err) {    
   if (err) throw err;    
   console.log('Da ket noi database'); 
}); 
module.exports = db; 

– Tạo file models/users.js code định nghĩa các hàm để tương tác vào mysql

var db = require('./database'); 
exports.list = function( callback) { 
    let sql = `SELECT *  FROM users`;
    db.query(sql, function(err, d) { callback(d); }  );
}
exports.create = function(data, callback ) { //hàm chèn user mới vào table 
    let sql = 'INSERT INTO users SET ?';
    db.query(sql, data, function(err, d) { callback(d) }  );    
} 
exports.update = function(id, data, callback) { 
    let sql = 'UPDATE users  SET ? WHERE idUser = ?';
    db.query(sql, [data, id], (err, d) => {
        if (err) throw err;
        callback();
    });    
} 
exports.read= function(id, callback) {
    let sql = 'SELECT * FROM users WHERE idUser = ?'    
    db.query(sql, id, (err, d) => {
        data = d[0]; 
        callback(data);
    });
} 

5. Tạo controller

– Mở file app.js, bạn sẽ thấy lệnh app.use(‘/users‘, usersRouter); . Đường route 5. Tạo controllerspan>đã được express tạo sẵn cho bạn dẫn vào router(controller) users. Cứ để vậy khỏi tạo nữa (nhưng nếu muốn có thể sửa hoặc tạo mới)

– Mở file routes/users.js và code:

var express = require('express');
var router = express.Router();
var modelUsers = require('./../models/users'); 

router.get('/',  (req, res) => { 
    modelUsers.list( function(listusers) { res.json(listusers)} ); 
});
router.post('/', (req, res) => {
    let data = req.body; 
    modelUsers.create(data , function(){
        res.json({thongbao:"Đã thêm  xong một user mới"});
    });
 });
 router.get('/:id', (req, res) => {
    let id = req.params.id;    
    modelUsers.read(id, function(u){
      res.json(u);
    });
 });
 router.put('/:id', (req, res)=> {
      let data = req.body;
      let id = req.params.id;
      modelUsers.update(id, data, function(){
        res.json({thongbao: 'Đã cập nhật user '});
      })
 });
 module.exports = router;

Test: Dùng postman để thực hiện test : xem danh sách user, xem chi tiết 1 user, thêm 1 user , cập nhật 1 user. Tất cả phải thành công nhé.

Việc chuẩn bị đã xong. Giờ thì gọi nó trong trang web thế nào? Mời bạn xem tiếp để biết sử dụng Restful API NodeJS.

Sử dụng hàm fetch() để gọi API

Trong Javascript, hàm fetch(url, options, callback) là một hàm dùng để gửi và nhận request  đến tài nguyên ở xa. Bạn dùng hàm này để thực hiện gọi các API

Dùng fetch để request với method GET

Sử dụng hàm fetch() để gọi API ấu trúc cơ bản của hàm fetch để gọi 1 tài nguyên ở xa với method get. Nếu khi request mà có lỗi gì đó thì phần .catch sẽ chạy. Còn kết quả từ server sẽ truyền tới .then trong biến response, Bạn sử dụng biến response này đ>Dùng fetch để request với method GETchuyển nó thành các dạng dữ liệu cần thiết để xử lý ở các .then sau

fetch('http://…')
.then(function(response) {
  //đánh giá response và chuyển dữ liệu cho .then sau
})
.then(function(data) {
  // xử lý dữ liệu và chuyển dữ liệu cho .then sau
})
.then(function(data) {
  // xử lý dữ liệu 
})
.catch(function(error) {
  console.log('Co loi : \n', error);
});

Ví dụ 1: Dùng fetch gọi api lấy danh sách user về và hiện ra trang web

– Mở routes/index.js và tạo route

router.get('/danhsachuser', (req, res) => {
  res.render("listusers");
});

– Tạo file views/listusers.ejs

<h1>Danh sách users</h1>'
<div id='listuser'></div>
<script>
let urlapi = "http://localhost:3000/users/"
fetch(urlapi)  
.then(function(res) {
    console.log(res);
    if(!res.ok) { throw new Error("Lỗi = " + res.status); }
    return res.json();
})
.then(function(data) {
    console.log(data);
    //hiện data ra web
})
.catch(function(error)  { 
    console.log("Lỗi: ", error);
})
</script>

Test: Vào http://localhost:3000/danhsachuser sẽ thấy thông tin trong console

– Hiện dữ liệu ra web: Code tại vị trí hiện data ra web ở trên:

let kq = document.getElementById('listuser');
data.forEach( u => {
   kq.innerHTML+=`<p>${u.ho} ${u.ten}</p>`;
});

Xem thử kết quả: http://localhost:3000/danhsachuser , sẽ thấy kết quả, định dạng thêm cho đẹp nhé.

ket-qua-request-api-doc-array-json.png

Ví dụ 2: Sử dụng fetch để gọi api lấy thông tin 1 user về và hiện ra trang web

1. Tạo route: Mở routes/index.js và code

router.get('/chitietuser/:id', (req, res) => {
  let id = req.params.id;
  res.render("chitietuser", {id:id});
});

2. Tạo views/chitietuser.ejs

<h1>Chi tiết user</h1>
<div id="chitietuser"></div>
<script> 
let urlapi = `http://localhost:3000/users/<%=id%>`;
fetch(urlapi)  
.then(function(res) {
    if(!res.ok) {throw new Error("Lỗi = " + res.status); }
    return res.json();
})
.then(function(data) {
    let str="";
    str+= "<p>Username: " + data.username+"</p>";
    str+= "<p>Họ: " + data.ho + "</p>";
    str+= "<p>Tên: " + data.ten + "</p>";
    str+= "<p>Tỉnh: " + data.tinh + "</p>";
    str+= "<p>Email: " + data.email + "</p>";
    str+= "<p>Sở thích: <br>" + data.sothich + "</p>";
    document.getElementById("chitietuser").innerHTML=str;
    console.log(data);
})
.catch(function(error)  { console.log("Lỗi: ", error);})
</script>

Test: vào http://localhost:3000/chitietuser/1 sẽ thấy thông tin user hiện ra trang

Dùng hàm fetch để gọi API với method POST

Hàm fetch(url, options) giúp gửi request đến tài nguyên ở xa, trong đó options là các cấu hình chi tiết cho hàm, bạn chỉ định method post trong tham số options này. Cách sử dụng thể hiện qua ví dụ sau:

– Tạo route dangky trong routes/index.js

router.get('/dangky', (req, res) => {
  res.render("dangky");
});

– Tạo file views/dangky.ejs

<form name="frmdk">
    <p>Username: <input type="text" name="username"></p&>Dùng hàm fetch để gọi API với method POSTword" name="password"></p>
    <p>Email: <input type="email" name="email"></p>
    <button type="button" onclick="dangky()">Đăng ký</button>
</form>
<script>
function dangky(){
   let un = document.frmdk.username.value;
   let pw = document.frmdk.password.value;
   let em = document.frmdk.email.value;
   let data = {username: un, password: pw, email:em}
    let url ="http://localhost:3000/users/";
    let options = {
        method: "POST",
        body: JSON.stringify(data),
        headers: {"Content-type": "application/json; charset=UTF-8"}
    }
    fetch(url, options)
    .then(response => response.json()) 
    .then (function(data){
        document.frmdk.reset();
        console.log(data);
    })
    .catch(err => console.log(err));
}
</script>

– Test: http://localhost:3000/dangky ==> nhập thông tin rồi nhắp Đăng ký sẽ lưu thành công vào database.

Sử dụng thư viện Axios 

Axios là một thư viện giúp bạn gửi http request đến các ứng dụng API. Axios được dùng cả ở trình duyệt hay Node.js. Sử dụng Restful API NodeJS sẽ dễ hơn với thư viện này.

Tạo một request với Axios

Khi cần tạo rerquest đến api ở xa, bạn dùng đối tượng axios và chỉ định method, url, data cho request Công thức chung để tạo một request với axios, như sau

axios({
  method: 'post',
  url: '/login',
  data: { user: 'test', lastName: 'test1' }
});

Sử dụng thư viện Axios 

ng-thức-get">Request với phương thức GET

Với request dạng get, có thể dùng như sau cho trực quan

axios.get(url)
.then(function (response) {
    console.log(response);
})
.catch(fun>Tạo một request với Axiossp; console.log(error);
});

Thực hiện request với phương thức POST

Khi cần tạo request dạng post, cấu trúc lệnh như sau:

axios.post(url, {
  firstName: 'First name',
  lastName: 'Last name'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
>Request với phương thức GET

Các alias tạo request tương ứng với các http method

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, con>Thực hiện request với phương thức POSTnfig]])
  • axios.patch(url[, data[, config]])

Ví dụ sử dụng axios

1. file routes/index.js

 router.get('/ax1', (req, res) => {
  res.render("ax1_listusers");
});

2. Tạo file views/ax1_listusers.ejs

<script src="https://unpkg.com/ax>Các alias tạo request tương ứng với các http method  ng>listuser"></div>
<script>
 var url = "http://localhost:3000/users/";
 axios.get(url)
  .then(function (response) {
   // console.log(response);
    let str="";
    for (i in response.data) {
        let motuser = response.data[i];
        console.log(motuser);
        str +=  "<p>"+  motuser.ho + " " + motuser.ten  +"</p>Ví dụ sử dụng axiosan>
    document.getElementById("listuser").innerHTML += str;
   })
  .catch(function (error) {
    console.log(error);
  });
</script>

3. Test: http://localhost:3000/ax1 , sẽ thấy danh sách users


Luyện tập: Mời bạn thực hiện luyện tập nhé:
Bài 1: Tạo form đăng ký, khi nhắp vào sẽ lưu vào database. Định dạng form cho đẹp
Bài 2: Tạo trang xem chi tiết user có tham số là id . Định dạng cho đẹp nhé
Bài 3: Tạo form cập nhật user có tham số là id , khi nhắp nút cập nhật sẽ lưu giá trị mới vào database
Bài 4: Tạo trang hiện danh sách users , có nút Sửa, Xóa. Khi nhắp vào sẽ thực hiện chức năng tương ứng