学无先后,达者为师

网站首页 编程语言 正文

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

栏目分类
最近更新