Thumbnail
Category: Lập trình

Kinh nghiệm npm - package

Date: November 28, 2020
29 views

1. Axios

Package gọi API

1.1 Cài đặt


npm install axios

1.2 Sử dụng


import axios from 'axios';
​
​
//getdata
axios.get('https://jsonplaceholder.typicode.com/todos')
  .then( response => {
    this.TodoData = response.data;
  }); 
}

1.3 Gọi axios có token


//get
const response = await axios.delete('/api/delete-task/' + id, {
  headers: {
    /**
       * get token saved from localStorage
    */
    Authorization: 'Bearer ' + localStorage.getItem('token'),
  }
});
​
​
//post
axios.post('/api/create-task',{
  name: this.title,
  description: this.description,
  color: this.color,
  token: ''
  }, {
  headers: {
    /**
       * get token saved from localStorage
    */
    Authorization: 'Bearer ' + localStorage.getItem('token'),
  }
})
.then( data => {
    /**
        * response.data.result
        * + true: => create success
        * + false: => create fail
     */
    if (data.data.result) {
      this.title = '';
      this.description = '';
      this.color = '#ccc';
      alert('Thêm thành công');
    }
    else alert('Thêm không thành công');
}); 

1.3.1 Thêm header default

Không cần phải thêm header vào mỗi khi gọi api, mà chỉ cần thêm vào file js chính là được (thường là app.js hoặc main.js)


axios.interceptors.request.use(req => {
  req.headers.authorization = 'Bearer ' + localStorage.getItem('token');
  return req;
});
​
//'Bearer ' + localStorage.getItem('token'):  => thay đổi cho phù hợp

https://www.npmjs.com/package/axios

2. uuid

Package tạo mã id không trùng

2.1 Cài đặt


npm install uuid

2.2 Sử dụng


import { v4 as uuidv4 } from 'uuid';
​
//gọi hàm uuidv4 tại nơi muốn sử dụng
addTodo(todo) {
  this.TodoData = [...this.TodoData, {id: uuidv4(),title: todo}];
}

https://www.npmjs.com/package/uuid


Copyright © 2025 All Right Reserved