日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

react用axios的 get/post請求/獲取數據

作者:Krlin_ 更新時間: 2022-07-02 編程語言

一、Post

通式

 axios.post('api地址',待傳入的參數)
   .then(function (response) {
      //handle success data
   })
    .catch(function (error) {
       //handle error satuation
       console.log(error)
   })
}

應用

第二個參數第一種寫法:直接傳字符串

  const posts_ = 'https://www.fastmock.site/mock/4f2f543c48ec3d334a328af2e83239e6/MockData/api/postDemo'

  const axios = require('axios');
   // 第一個參數是post接口地址,第二個參數是往post寫入數據,這里是獲取表單的值
  axios.post(posts_, PostVal)
       .then(function (response) {
          //response.config.data 獲取表單值的地方
           console.log(response.config.data)
        })
    	.catch(function (error) {
           console.log(error)
    })

第二個參數的另一種寫法:傳json格式的對象

  const axios = require('axios');
  axios.post('https://www.fastmock.site/mock/4f2f543c48ec3d334a328af2e83239e6/MockData/api/postDemo', {
   		"jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "PostVal": PostVal,
        },
        "id": 1,
        "auth": null
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

二、Get

通式

 axios.get('api地址')
   .then(function (response) {
      //handle success data
   })
    .catch(function (error) {
       //handle error satuation
       console.log(error)
   })
}

應用

const getApi = () => {
        axios.get(api)
            .then(function (response) {
                //handle success data
                const result = response.data.data
                setUserName(result.userName);
                setEmail(result.email);
                setUserId(result.userId);
                setMsg(response.data.msg);
            })
            .catch(function (error) {
                //handle error satuation
                console.log(error)
            })
    }

三、報錯提示:console.log(response)返回[object,object]

  1. JSON.stringfy(response)將response對象轉為字符串,但是不好獲取里面的屬性;
    希望有其他更好的解決辦法

參考文章
axios 獲取post數據

四、完整代碼

import React, { useRef, useState } from 'react'
import axios from 'axios'
import styles from "./index.less"
export default () => {

    const [userName, setUserName] = useState()
    const [email, setEmail] = useState()
    const [userId, setUserId] = useState()
    const [msg, setMsg] = useState()
    const api = 'https://www.fastmock.site/mock/4f2f543c48ec3d334a328af2e83239e6/MockData/api/mock'

    const getApi = () => {
        axios.get(api)
            .then(function (response) {
                //handle success data
                const result = response.data.data
                setUserName(result.userName);
                setEmail(result.email);
                setUserId(result.userId);
                setMsg(response.data.msg);
            })
            .catch(function (error) {
                //handle error satuation
                console.log(error)
            })
    }

    const [PostVal, setPostValue] = useState();
    const postContent = useRef(null);

    const posts_ = 'https://www.fastmock.site/mock/4f2f543c48ec3d334a328af2e83239e6/MockData/api/postDemo'
    function postApi() {
        if (postContent.current.value.trim() !== '') {
            //the second program uses to get post content
            axios.post(posts_, PostVal)
                .then(function (response) {
                    //response.config.data 獲取表單值的地方
                    console.log(response.config.data)
                })
                .catch(function (error) {
                    console.log(error)
                })
        }
        else {
            alert('please input something!')
        }

    }

    function handleSubmit() {
        if (postContent.current.value.trim() !== '') {
            return setPostValue(postContent.current.value.trim());
        }
        alert('please input something!')
    }

    return (
        <div className={styles.InterFace}>
            <h3>Get 請求獲取接口數據</h3>
            <button type="button" onClick={getApi}>Get api</button>
            <div>
                <p> <b>userName: </b>{userName}</p>
                <p><b>userId: </b>{userId}</p>
                <p><b>email: </b>{email}</p>
                <p><b>msg: </b>{msg}</p>
            </div>
            <h3>Post 請求獲取接口數據</h3>
            <div>
                <input type="text" ref={postContent} />
                <p><b>post value: </b>{PostVal}</p>
                <button type="button" onClick={handleSubmit}>Submit</button>

                <button type="button" onClick={postApi}>Post api</button>
            </div>
        </div>
    )
}

五、自造測試接口

fastmock
使用步驟參考官方文檔教程

原文鏈接:https://blog.csdn.net/weixin_46353030/article/details/123458121

欄目分類
最近更新