Tạo request api trong react

Tạo request api trong react hướng dẫn 2 cách truy cập đến api, đó là lệnh fetch của Javacript và thư viện Axios.


Trong thời đại lập trình tương tác hiện nay, nhiều website cung cấp các dịch vụ của mình ra ngoài để cho gọi từ xa. Bạn có thể request API  đến các website đó để có các thông tin cần thiết. Ví dụ tạo request đến openweathermap.org để có thông tin thời tiết, tạo request đến unsplash.com để có các hình ảnh chia sẻ chất lượng cao, request api đến Google, Facebook, Youtube …

Request API cũng thông qua http như request web, nhưng kết trả về không phải là khối code html, mà là dữ liệu có cấu trúc (json, xml)

Tạo request API như thế nào

Bạn có thể dùng cách cơ bản và đơn giản là lệnh fetch trong javascript để tạo request đến 1 tài nguyên api được cung cấp. Cách thứ hai là bạn có thể cài thư viện axios vào để thực hiện request api.

Sau đây là hướng dẫn cách đăng ký tài khoản , tạo app ở unsplash để sử dụng api của website này.

Đăng ký, tạo ứng dụng và lấy key trong Unsplash

Unsplash là 1 website chia sẻ hình ảnh chất lượng cao, miễn phí. Unsplash cũng cung cấp API để gọi từ xa.

1. Đăng ký: Vào  https://unsplash.com/developers   đăng ký với tư cách developers. Đăng ký xong thì login vào.

2. Tạo app : nhắp nút New Aplication để tạo, xong lưu access key và serect key

Tạo ứng dụng ở unsplash
Tạo ứng dụng ở unsplash
Tạo ứng dụng ở unsplash

3. Access key và Secret key hiện ra , lưu lại để dùng nhé

Key của unsplash cung cấp

4. Xem tài liệu hướng dẫn:

Vào Documentation => Search photo by keywords để xem cách dùng

Tài liệu hướng dẫn search hình ảnh ở unsplash

Tạo Form search picture

– Tạo file src/FormSearchPic.js

import { timesSeries } from 'async';
import React from 'react';
class FormSearchPic extends React.Component{
constructor(){
    super();
    this.state = {pictures:[]};
    this.tukhoa = React.createRef();
}
timhinh = (e) => {
    let tk = this.tukhoa.current.value;
    alert(tk);
}
render(){
const kq=
<div>
    <form className="p-2">
        <input ref={this.tukhoa} className="form-control"/>
        <button  onClick={this.timhinh} type="button" 
        className="btn btn-primary">Tìm hình</button>
    </form>
    <div id="kqSeachPic"/>
</div>
return (kq)
}
}
export default FormSearchPic

– Nhúng vào App.js

import FormSearchPic from './FormSearchPic';

– Hiện form trong layout

<Col sm={9} className="bg-info" id="maindata">  
     <FormSearchPic/>
</Col>

– Test : Gõ từ khóa rồi nhắp nút , sẽ thấy hiện từ khóa ra

Tạo reqest API với lệnh fetch

Code lại trong hàm tìm hình ở trên

timhinh = (e) => {
    let tk = this.tukhoa.current.value;
    let page=1;
    let per_page=20;
    let url=`https://api.unsplash.com/search/photos?query=${tk}&page=${page}&per_page=${per_page}&client_id=ACCESS_KEY_CỦA_BẠN`;
    fetch( url)
    .then(function(res) {
        if (!res.ok) throw Error(res.statusText);  
        return res.json();  //dùng text() nếu dạng text
    })
    .then(function(data) { //  data để hứng dữ luệu từ phía trên
        let pictures = data.results;
        //console.log(pictures);
        let listPic=[];
        pictures.forEach(function( p , index){
            console.log(p.urls.regular);
            listPic.push(<img src={p.urls.regular} height="150" />)
        })
        ReactDOM.render(listPic, document.getElementById("kqSeachPic"));
    })
    .catch(function(error) {
         console.log('Có lỗi nè : \n', error);
    });
}

Tạo request API với thư viện Axios

Tham khảo thêm cách dùng axios ở địa chỉ : https://longnv.name.vn/lap-trinh-nodejs/su-dung-restful-api-nodejs

– Cài thư viện Axios: npm install axios

– Code trong hàm tìm hình ở trên với thư viện Axios

async timhinh(e)  {
    let tk = this.tukhoa.current.value;
    let page=1;
    let per_page=20;
    let url=`https://api.unsplash.com/search/photos?query=${tk}&page=${page}&per_page=${per_page}&client_id=ACCESS_KEY_CỦA_BAN`;
    await axios.get(url)    
    .then(function(res) { 
        let pictures = res.data.results;
        let listPic=[];
        pictures.forEach(function( p , index){
            console.log(p.urls.regular);
            listPic.push(<img src={p.urls.regular} height="150" />)
        })
        ReactDOM.render(listPic, document.getElementById("kqSeachPic"));
    })
    .catch(function(error) { console.log('Có lỗi nè : \n', error); });
}

Trên đây là ví dụ về cách dùng fetch và axios để tạo request api trong react. Bạn dựa vào các ví dụ cụ thể ở đây để request api ở các nơi khác nhé.