axios 用來做 http 請求的其中一種工具。 (call api會用到) https://axios-http.com/docs/intro 1. 安裝 axios(如果還沒安裝) ```sh npm install axios ``` 2. 引入 axios ```javascript import axios from 'axios'; const API_URL = 'https://jsonplaceholder.typicode.com/posts'; // 假設這是你測試用的 API ``` # 新增資料 - POST ```axios.post(url,{para})``` ```javascript const createPost = async () => { try { const response = await axios.post(API_URL, { title: 'New Post', body: 'This is a new post', userId: 1 }); console.log('Created:', response.data); } catch (error) { console.error('Error creating post:', error); } }; createPost(); ``` post的時候要丟的**參數長相**,要去看**後端給的規格**、或問後端工程師api要收的參數規格(假如沒有文件可看的話,就用問的)。 **參數長相**要注意的細節包括,值的型別(字串?數字?陣列?物件?屬性名稱要一模一樣?)、是否大小寫敏感?字串的話是JSON的格式?或 Query String?還是formData? ### 補充說明: 1️⃣ **JSON 格式** ```JSON(JavaScript Object Notation)```是一種結構化的資料格式,適合傳輸 複雜的結構化數據。 通常用在 RESTful API 或 GraphQL API 的請求與回應中。 🔹 範例(從 API 獲取 JSON): ```json { "products": [ { "id": 1, "name": "手機", "price": 10000 }, { "id": 2, "name": "筆電", "price": 30000 } ] } ``` 🔹 使用 Axios 爬取 JSON API: ```javascript import axios from 'axios'; async function fetchProducts() { const response = await axios.get('https://example.com/api/products'); console.log(response.data); // 取得 JSON 內容 } fetchProducts(); ``` ✅ **適合用來處理 結構化資料,例如**: 商品清單 使用者資訊 文章內容 2️⃣ **Query String**格式 Query String 是 URL 中的參數,常見於 GET 請求,用來傳遞簡單的數據(如搜尋關鍵字、篩選條件)。 格式是 key=value&key2=value2,常見於 搜尋引擎、篩選功能、API 查詢。 🔹 範例: ```plaintext https://example.com/search?query=手機&sort=price ``` 🔹 用 Axios 發送 Query String 請求: ```javascript const params = { query: '手機', sort: 'price' }; const response = await axios.get('https://example.com/search', { params }); console.log(response.data); ``` 這樣發送的請求實際上是: ```plaintext GET https://example.com/search?query=手機&sort=price ``` ✅ 適合用來: **搜尋關鍵字 篩選條件 API 查詢參數** 🔹 **JSON vs Query String 差異** |特性| JSON 格式 |Query String 格式| |---|-------------|-----------------| |用途|結構化資料(如 API 回應) |查詢、篩選、搜尋參數| |傳輸方式| POST / GET / PUT / DELETE |主要用 GET| |範例| { "id": 1, "name": "手機" } |?id=1&name=手機| |適用場景| 商品、文章、用戶數據 |搜尋、篩選、簡單 API| 📌**如何決定用哪種方式?** 如果你在 觀察 API 回應,發現是 JSON,那就用 axios.get(url) 解析 JSON。 如果你在 URL 上看到 ?key=value,表示 API 可能用 Query String,那就用 { params } 來傳遞參數。 你現在要爬的網站是用哪一種方式?👀 --- # 讀取資料 - GET ```javascript const getPosts = async () => { try { const response = await axios.get(API_URL); console.log('Posts:', response.data); } catch (error) { console.error('Error fetching posts:', error); } }; getPosts(); ``` # Update(更新資料 - PUT / PATCH) PUT:完整更新 ```javascript const updatePost = async (id) => { try { const response = await axios.put(`${API_URL}/${id}`, { title: 'Updated Title', body: 'Updated content', userId: 1 }); console.log('Updated:', response.data); } catch (error) { console.error('Error updating post:', error); } }; ``` updatePost(1); # PATCH:局部更新 ```javascript const patchPost = async (id) => { try { const response = await axios.patch(`${API_URL}/${id}`, { title: 'Partially Updated Title' }); console.log('Partially Updated:', response.data); } catch (error) { console.error('Error patching post:', error); } }; patchPost(1); ``` # Delete(刪除資料 - DELETE) ```javascript const deletePost = async (id) => { try { await axios.delete(`${API_URL}/${id}`); console.log(`Post ${id} deleted`); } catch (error) { console.error('Error deleting post:', error); } }; deletePost(1); ``` 這些範例可以直接使用,若有需要 headers 或 params,可以在 axios 方法的第二個參數中加入,例如: ```javascript axios.get(API_URL, { params: { userId: 1 } }); // 只獲取 userId=1 的資料 ```