Office.in.th
คู่มือระบบ เนื้อหาผ่านการตรวจสอบแล้ว

การทำงานร่วมกับ Axios

Axios เป็น JavaScript Library ที่ช่วยในการดึงข้อมูลจาก API ได้อย่างสะดวก รองรับ Promise และมีฟีเจอร์สำหรับจัดการคำขอ (Request) และคำตอบ (Response)


1. ความเข้าใจเกี่ยวกับ Axios และ Alpine.js

Axios เป็น JavaScript Library ที่ช่วยในการดึงข้อมูลจาก API ได้อย่างสะดวก รองรับ Promise และมีฟีเจอร์สำหรับจัดการคำขอ (Request) และคำตอบ (Response)

  • การทำงานร่วมกับ Alpine.js ทำให้คุณสามารถสร้าง Component ที่ดึงข้อมูลแบบ Dynamic พร้อมจัดการ Error ได้ง่าย

2. การติดตั้ง Axios

ติดตั้ง Axios ผ่าน CDN

เพิ่มลิงก์ CDN ของ Axios ใน <head>:

<head>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>

3. การดึงข้อมูลด้วย Axios

ตัวอย่าง 1: ดึงข้อมูลและแสดงผล
<div x-data="{ posts: [], fetchPosts() {
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                this.posts = response.data;
            })
            .catch(error => {
                console.error('Error fetching posts:', error);
            });
    } }" x-init="fetchPosts()">
    <h2>Posts</h2>
    <ul>
        <template x-for="post in posts" :key="post.id">
            <li>
                <h3 x-text="post.title"></h3>
                <p x-text="post.body"></p>
            </li>
        </template>
    </ul>
</div>

คำอธิบาย:

  • ใช้ axios.get() เพื่อดึงข้อมูลจาก API
  • ข้อมูลจากคำตอบ (response.data) ถูกเก็บใน State posts และแสดงใน <ul>

4. การจัดการ Loading และ Error

ตัวอย่าง 2: เพิ่มสถานะ Loading และ Error
<div x-data="{ posts: [], loading: false, error: '', fetchPosts() {
        this.loading = true;
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                this.posts = response.data;
            })
            .catch(error => {
                this.error = 'Failed to fetch posts.';
                console.error(error);
            })
            .finally(() => {
                this.loading = false;
            });
    } }" x-init="fetchPosts()">
    <template x-if="loading">
        <p>Loading...</p>
    </template>
    <template x-if="error">
        <p x-text="error" class="text-red-500"></p>
    </template>
    <ul>
        <template x-for="post in posts" :key="post.id">
            <li>
                <h3 x-text="post.title"></h3>
                <p x-text="post.body"></p>
            </li>
        </template>
    </ul>
</div>

คำอธิบาย:

  • ใช้ State loading และ error เพื่อจัดการสถานะการโหลดข้อมูลและข้อผิดพลาด
  • แสดงข้อความ "Loading..." หรือข้อความ Error ตามสถานะปัจจุบัน

5. การส่งข้อมูลด้วย Axios

ตัวอย่าง 3: ส่งข้อมูล (POST Request)
<div x-data="{ title: '', body: '', submitPost() {
        axios.post('https://jsonplaceholder.typicode.com/posts', {
            title: this.title,
            body: this.body
        })
        .then(response => {
            console.log('Post created:', response.data);
            alert('Post created successfully!');
        })
        .catch(error => {
            console.error('Error creating post:', error);
        });
    } }">
    <form @submit.prevent="submitPost()">
        <label>
            Title:
            <input type="text" x-model="title" class="block mb-2">
        </label>
        <label>
            Body:
            <textarea x-model="body" class="block mb-2"></textarea>
        </label>
        <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded">Submit</button>
    </form>
</div>

คำอธิบาย:

  • ใช้ axios.post() ส่งข้อมูล title และ body ไปยัง API
  • แสดงข้อความยืนยันเมื่อคำขอสำเร็จ

6. การส่งพารามิเตอร์ใน Request

ตัวอย่าง 4: การส่ง Query Parameters
<div x-data="{ userId: 1, posts: [], fetchUserPosts() {
        axios.get('https://jsonplaceholder.typicode.com/posts', {
            params: { userId: this.userId }
        })
        .then(response => {
            this.posts = response.data;
        })
        .catch(error => {
            console.error('Error fetching user posts:', error);
        });
    } }" x-init="fetchUserPosts()">
    <label>
        User ID:
        <input type="number" x-model="userId" @change="fetchUserPosts()" class="block mb-4">
    </label>
    <ul>
        <template x-for="post in posts" :key="post.id">
            <li>
                <h3 x-text="post.title"></h3>
                <p x-text="post.body"></p>
            </li>
        </template>
    </ul>
</div>

คำอธิบาย:

  • ใช้ axios.get() พร้อม params เพื่อส่ง Query Parameters
  • ข้อมูลที่แสดงเปลี่ยนไปตามค่า userId

7. การจัดการ Headers ใน Axios

ตัวอย่าง 5: เพิ่ม Custom Headers
<div x-data="{ posts: [], fetchPosts() {
        axios.get('https://jsonplaceholder.typicode.com/posts', {
            headers: { Authorization: 'Bearer YOUR_TOKEN_HERE' }
        })
        .then(response => {
            this.posts = response.data;
        })
        .catch(error => {
            console.error('Error fetching posts:', error);
        });
    } }" x-init="fetchPosts()">
    <ul>
        <template x-for="post in posts" :key="post.id">
            <li>
                <h3 x-text="post.title"></h3>
                <p x-text="post.body"></p>
            </li>
        </template>
    </ul>
</div>

คำอธิบาย:

  • ใช้ headers ในคำขอเพื่อเพิ่ม Authorization Token หรือข้อมูลอื่น ๆ ที่ต้องการ

8. การดึงข้อมูลแบบ Asynchronous ด้วย Async/Await

ตัวอย่าง 6: ใช้ Async/Await
<div x-data="{ posts: [], async fetchPosts() {
        try {
            const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
            this.posts = response.data;
        } catch (error) {
            console.error('Error fetching posts:', error);
        }
    } }" x-init="fetchPosts()">
    <h2>Posts</h2>
    <ul>
        <template x-for="post in posts" :key="post.id">
            <li>
                <h3 x-text="post.title"></h3>
                <p x-text="post.body"></p>
            </li>
        </template>
    </ul>
</div>

คำอธิบาย:

  • ใช้ async/await เพื่อทำให้โค้ดอ่านง่ายและจัดการข้อผิดพลาดได้สะดวก

9. ข้อควรระวังในการใช้ Axios

  1. การจัดการข้อผิดพลาด:
    • ตรวจสอบสถานะคำขอ (status code) และแสดงข้อความเตือนผู้ใช้ในกรณีที่เกิดข้อผิดพลาด
  2. การรักษาความปลอดภัย:
    • อย่าเก็บข้อมูลสำคัญ เช่น Token ในโค้ด JavaScript แบบ Public
  3. การจัดการการโหลดข้อมูลซ้ำ:
    • ควบคุมการส่งคำขอซ้ำเพื่อลดภาระของ API Server

สรุป

ในบทนี้ คุณได้เรียนรู้การทำงานร่วมกันระหว่าง Axios และ Alpine.js สำหรับการดึงข้อมูลแบบ Dynamic และจัดการข้อผิดพลาด ตัวอย่างครอบคลุมการดึงข้อมูล, ส่งข้อมูล, การจัดการ Loading และ Error รวมถึงการส่ง Query Parameters และ Custom Headers การรวม Axios กับ Alpine.js ช่วยให้คุณพัฒนาแอปพลิเคชันที่ตอบสนองและใช้งานง่ายได้อย่างมีประสิทธิภาพ!

Office.in.th Custom Service

ต้องการพัฒนาระบบหรือปรับแต่งจากโครงสร้างนี้?

Office.in.th รับพัฒนาและออกแบบ Enterprise Web Application, API Integration และระบบบริหารงานภาครัฐ/เอกชน พร้อมการสนับสนุนระยะยาว

ดูบริการรับพัฒนาซอฟต์แวร์