iT邦幫忙

1

React 學習筆記_19(在React中使用Axios調用JSON-Server數據)

Fandix 2020-04-12 15:24:2014924 瀏覽

簡介

axios 是一個基於 Promise 的 HTTP 客戶端,專門服務於瀏覽器和 node.js 。

功能

  • 在瀏覽器中傳送 XMLHttpRequests 請求
  • 在 node.js 中傳送 http 請求
  • 支援 Promise API
  • 攔截請求和響應
  • 轉換請求和響應資料
  • 自動轉換 JSON 資料格式

建立Axios

使用JSON-Server建立一個數據庫並且使用Axios對數據庫中的數據進行操作。

Step 1 : 建立一個React Project並安裝Axios

npm install axios
yarn add axios

Step 2 : 建立Axios的Component以提供呼叫

import _axios from "axios"

const axios = (baseURL) => {
    //建立一個自定義的axios
    const instance = _axios.create({
            baseURL: baseURL || 'http://localhost:3003', //JSON-Server端口位置
            timeout: 1000,
        });

     return instance;
}

export {axios};
export default axios();

Axios API實例

運用axios的API對JSON-Server數據庫中的數據進行操作。

GET (取得資料)

import React from "react";
import axios from "./axios";

class App extends React.Component
{
    GET = async() => {
        try 
        {
            //取得數據庫http://localhost:3003/posts的數據
            const Data = await axios.get("/posts"); 
            console.log(Data.data);
        } 
        catch (error) 
        {
            alert("GET Error!!");    
        }  
    };
    
    render()
    {
        return(
            <div className="get">
                <button onClick={this.GET}>Get</button>
            </div>
        );
    };
};

當按下GET按鈕後取得http://localhost:3003/posts的數據
https://ithelp.ithome.com.tw/upload/images/20200411/20124767yYz0dITpkM.png

POST (新增資料)

import React from "react";
import axios from "./axios";

class App extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            id:"",
            title : "",
            author : ""
        }
    };

    handleChange = (e) => {
        //Step 1:取得輸入的數值
        const value = e.target.value;
        //Step 2:取得輸入的input名子
        const name = e.target.name;
        //Step 3:更改State數據
        this.setState({
            [name]:value
        });
    };
    //-------------------------------------------------//
    POST = () => {
        //Step 1:取得state數據
        const product = {...this.state};
        //Step 2:新增到JSON-Server數據庫中 
        axios.post("/posts",product);
    };
    //-------------------------------------------------//    
        
    render()
    {
        retrun(
            <div className="post">
                    <label>title</label>
                    <textarea 
                      name="title" 
                      value={this.state.title} 
                      onChange={this.handleChange}
                    />
                    <label>author</label>
                    <textarea 
                      name="author" 
                      value={this.state.author} 
                      onChange={this.handleChange}
                    />
                    <button onClick={this.POST}>POST</button>
             </div>
        );
    };
};

https://ithelp.ithome.com.tw/upload/images/20200411/20124767FptbxMFmcf.png

使用GET按鈕來取得當前數據庫數據以確認是否新增了新的數據到數據庫中
https://ithelp.ithome.com.tw/upload/images/20200411/20124767t20rqq0hjw.png

PUT (更新資料)

import React from "react";
import axios from "./axios";

class App extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            id:"",
            title : "",
            author : ""
        }
    };

    handleChange = (e) => {
        //Step 1:取得輸入的數值
        const value = e.target.value;
        //Step 2:取得輸入的input名子
        const name = e.target.name;
        //Step 3:更改State數據
        this.setState({
            [name]:value
        });
    };
    //-------------------------------------------------//
    PUT = () => {
        //Step 1:取得state數據
        const product = {...this.state};
        //Step 2:更新指定JSON-Server數據庫中指定的id數據
        axios.put(`posts/${this.state.id}`,product)
    };
    //-------------------------------------------------//    
        
    render()
    {
        return(
             <div className="put">
                    <label>ID</label>
                    <input 
                      type="text" 
                      name="id" 
                      value={this.state.id} 
                      onChange={this.handleChange}
                    />
                    <label>title</label>
                    <textarea 
                      name="title" 
                      value={this.state.title} 
                      onChange={this.handleChange}
                    />
                    <label>author</label>
                    <textarea 
                      name="author" 
                      value={this.state.author} 
                      onChange={this.handleChange}
                    />
                    <button onClick={this.PUT}>PUT</button>
                </div>
        );
    }; 
};    

https://ithelp.ithome.com.tw/upload/images/20200411/20124767nprICLCMug.png
使用GET按鈕來取得當前數據庫數據以確認是否更新了指定id的數據
https://ithelp.ithome.com.tw/upload/images/20200411/20124767Gke5DLFMWD.png

DELETE (刪除資料)

import React from "react";
import axios from "./axios";

class App extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            id:"",
            title : "",
            author : ""
        }
    };

    handleChange = (e) => {
        //Step 1:取得輸入的數值
        const value = e.target.value;
        //Step 2:取得輸入的input名子
        const name = e.target.name;
        //Step 3:更改State數據
        this.setState({
            [name]:value
        });
    };
    //-------------------------------------------------//
    Delete = () => {
        const product = {...this.state};
        axios.delete(`posts/${this.state.id}`,product)
    };
    //-------------------------------------------------//
    
    render()
    {
        return(
            <div className="delete">
                    <label>ID</label>
                    <input 
                      type="text" 
                      name="id" 
                      value={this.state.id} 
                      onChange={this.handleChange}
                    />
                    <button onClick={this.Delete}>Delete</button>
            </div>
        );
    };   
};    

指定要刪除數據的id:
輸入指定要刪除的id
使用GET按鈕來取得當前數據庫數據以確認是否將指定id的數據刪除
https://ithelp.ithome.com.tw/upload/images/20200411/20124767tfEGNs83Qv.png

參考資料 :
GitHub-axios
axios 基本使用 & Config
Axios Crash Course | HTTP Library


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言