Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Khi bạn tham gia vào phát triển với Vue 3 hoặc React, thì thư viện Axios thường được coi là lựa chọn mặc định để thực hiện các yêu cầu HTTP, thiết lập giao tiếp giữa ứng dụng của bạn và máy chủ. Vậy Axios là cái gì và làm thế nào chúng ta có thể sử dụng nó? Trong hướng dẫn này, vinasupport.com sẽ giúp bạn hiểu rõ hơn về các khái niệm cơ bản này.

Axios là gì?

Axios là một promise-based HTTP Client cho NodeJS và trình duyệt. Nó được sử dụng để gửi các HTTP Request tới một Web URL và nhận dữ liệu response trả về.

Để hiểu về Promise là gì? Các bạn vui lòng tham khảo bài viết sau:

Các tính năng của Axios

  • Tạo các yêu cầu XMLHttpRequests từ trình duyệt
  • Tạo các yêu cầu Http từ node.js
  • Hỗ trợ Promise API
  • Yêu cầu chặn và phản hồi
  • Chuyển đổi dữ liệu yêu cầu và phản hồi
  • Huỷ bỏ yêu cầu
  • Cancel requests
  • Timeouts
  • Tự động yêu cầu tuần tự hóa nội dung thành:
    • JSON (application/json)
    • Multipart / FormData (multipart/form-data)
    • URL encoded form (application/x-www-form-urlencoded)
  • Đăng biểu mẫu HTML dưới dạng JSON
  • Xử lý dữ liệu JSON tự động theo phản hồi
  • Ghi lại tiến trình cho trình duyệt và node.js với thông tin bổ sung (tốc độ, thời gian còn lại)
  • Thiết lập giới hạn băng thông cho node.js
  • Tương thích với FormData và Blob tuân thủ thông số kỹ thuật (bao gồm node.js)
  • Hỗ trợ client site để bảo vệ khỏi XSRF

Cài đặt Axios với Vue 3

Chúng ta cài bằng lệnh npm như sau:

npm install axios vue-axios

Ở file main.js của Vue 3 chúng ta thêm như sau:

import { createApp } from 'vue'
import CouponApp from './CouponApp.vue'

import axios from 'axios'
import VueAxios from 'vue-axios'


// createApp(App).mount('#app')
createApp(CouponApp).use(VueAxios, axios).mount('#coupon-app')

Sau đó trong Handsontable component mình gọi như sau:

Mình đưa đoạn script gọi axios ở methods created của Vue 3 và update dữ liệu data của Handsontable

<script>
import { HotTable, HotColumn } from '@handsontable/vue3';
import 'handsontable/dist/handsontable.full.css';
import { registerAllModules } from 'handsontable/registry';

// register Handsontable's modules
registerAllModules();


export default {
  name: 'CouponDataTable',
  data() {
    return {
      settings: {
        stretchH: 'all',
        licenseKey: 'non-commercial-and-evaluation',
        //... other options
      },
      data: [],
    };
  },
  components: {
    HotTable,
    HotColumn,
  },
  created() {
    this.axios.get('http://vinasupport.com/api/v1/coupon-code/').then(response => this.data = response.data)
  },
  watch: {
    data (newData) {
      // Update Table data with newData
      this.$refs.CouponDataTable.hotInstance.updateSettings({
        data: newData,
      });
    },
  },
};
</script>

<template>
  <hot-table ref="CouponDataTable" :settings="settings" :data="data" >
    <hot-column title="ID" read-only="true" data="coupon_code_id">
    </hot-column>
    <hot-column title="Code" data="code">
    </hot-column>
    <hot-column title="Title" data="title">
    </hot-column>
    <hot-column title="Discount" data="discount">
    </hot-column>
    <hot-column title="Expired Date" data="expired_date">
    </hot-column>
  </hot-table>
</template>

Kết quả!

Các phương thức thường được sử dụng với Axios

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

Một số cách dùng Axios

Đây là 1 ví dụ đầy đủ về cách sử dụng Axios

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

Trong đó.

  • .then: là hàm xử lý dữ liệu trả về thành công
  • .catch: là hàm xử lý nếu yêu cầu trả về có lỗi
  • .finally: là hàm luôn luôn xử lý cho dù dữ liệu có trả về thành công hay có lỗi.

Trường hợp bạn muốn xử lý bất đồng bộ với Axios thì hãy sử dụng async và await

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Gửi dữ liệu với method POST

axios.post('/login', {
  firstName: 'Finn',
  lastName: 'Williams'
})
.then((response) => {
  console.log(response);
}, (error) => {
  console.log(error);
});

Chống XSRF

const options = {
  method: 'post',
  url: '/login',
  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',
};

// send the request
axios(options);

Gửi nhiều request một lúc

axios.all([
  axios.get('https://api.github.com/users/mapbox'),
  axios.get('https://api.github.com/users/phantomjs')
])
.then(responseArr => {
  //this will be executed only when all requests are complete
  console.log('Date created: ', responseArr[0].data.created_at);
  console.log('Date created: ', responseArr[1].data.created_at);
});

Gửi request với một header

const options = {
  headers: {'X-Custom-Header': 'value'}
};

axios.post('/save', { a: 10 }, options);

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *