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