当前位置: 首页 > 工具软件 > react-query > 使用案例 >

react--数据请求

徐奇逸
2023-12-01

get请求

静态数据        不方便修改,而且只能通过本页面进行修改

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Hello World</title>
        <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script crossorigin src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
        <!--数据请求-->
        <script src="https://cdn.bootcss.com/fetch/2.0.3/fetch.min.js"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>
<script type="text/babel">
    class Fetch_get extends React.Component{
        constructor(props){
            super(props)
            this.state = {
                arr:[
                    {"id":"123001","name":"xiaoming"},
                    {"id":"123002","name":"xiaobing"},
                    {"id":"123003","name":"xiaona"}
                ]
            }
        }
        render(){
            return (
                <div>
                    <ul>
                        {
                            this.state.arr.map((ele,index,arr)=>{
                                return <li key={index}>{ele.name}</li>
                            })
                        }
                    </ul>
                </div>
            )
        }
    }
    ReactDOM.render(
        <Fetch_get></Fetch_get>, 
        document.getElementById('root') 
    );
</script>

请求json数据,完成页面渲染

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Hello World</title>
        <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script crossorigin src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
        <!--数据请求-->
        <script src="https://cdn.bootcss.com/fetch/2.0.3/fetch.min.js"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>
<script type="text/babel">
    class Fetch_get extends React.Component{
        constructor(props){
            super(props)
            this.state = {
                arr:[]
            }
        }
        render(){
            return (
                <div>
                    <ul>
                        {
                            this.state.arr.map((ele,index,arr)=>{
                                return <li key={index}>{ele.name}</li>
                            })
                        }
                    </ul>
                </div>
            )
        }
        componentDidMount(){
            var url = "data.json"
            var option = {
                methods:"get"
            }
            fetch(url,option).then((res)=>{
                return res.json()
            }).then((res)=>{
                // 请求到的数据
                console.log(res)
                // 修改state
                this.setState({
                    arr:res
                })
                // 打印输出 
                console.log(this.state.arr)
            })
        }
    }
    ReactDOM.render(
        <Fetch_get></Fetch_get>, 
        document.getElementById('root') 
    );
</script>

数据库

为了方便数据的操作,我们平时在页面上看到的数据一般都是在线数据,通过后台系统管理,能够很方便实现对数据的修改

在此,就不多做演示!!!

在线接口

书写数据接口,通过后台操作,读取数据库数据,并形成接口的形式,我们需要对数据进行操作的时候,直接操作接口即可

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Hello World</title>
        <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script crossorigin src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
        <!--数据请求-->
        <script src="https://cdn.bootcss.com/fetch/2.0.3/fetch.min.js"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>
<script type="text/babel">
    [{"id":"123001","name":"xiaoming"},{"id":"123002","name":"xiaobing"},{"id":"123003","name":"xiaona"}]
    class Fetch_get extends React.Component{
        constructor(props){
            super(props)
            this.state = {
                arr:[]
            }
        }
        render(){
            return (
                <div>
                    <ul>
                        {
                            this.state.arr.map((ele,index,arr)=>{
                                return <li key={index}>{ele.name}</li>
                            })
                        }
                    </ul>
                </div>
            )
        }
        componentDidMount(){
            //请求在线接口
            var url = "http://www.taoquan.store/robot/getUsers.php"
            var option = {
                methods:"get"
            }
            fetch(url,option).then((res)=>{
                return res.json()
            }).then((res)=>{
                // 请求到的数据
                console.log(res.users)
                // 修改state
                this.setState({
                    arr:res.users
                })
                // 打印输出 
                console.log(this.state.arr)
            })
        }
    }
    ReactDOM.render(
        <Fetch_get></Fetch_get>, 
        document.getElementById('root') 
    );
</script>

post数据请求

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Hello World</title>
        <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script crossorigin src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
        <!--数据请求-->
        <script src="https://cdn.bootcss.com/fetch/2.0.3/fetch.min.js"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>
<script type="text/babel">
    class Com extends React.Component{
        constructor(props){
            super(props)
            this.state = {
                num:1
            }
        }
        render(){
            return (
                <div>
                    <ul>
                        <li>1</li>
                    </ul>
                </div>
            )
        }
        componentDidMount(){
            var url = 'http://127.0.0.1:8899/api/insertData'
            var options = {
                method: 'POST',
                  headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                  },
                  body: 'name=1&sex=2&email=3&phone=4&address=5'
            }
            fetch(url,options)
            .then((res)=>{
                return res.json()
            })
            .then((res)=>{
                console.log(res)
            })
        }
    }
    ReactDOM.render(
        <Com></Com>, 
        document.getElementById('root') 
    );
</script>

核心代码,需注意

            var url = 'http://127.0.0.1:8899/api/insertData'
                var options = {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'name=1&sex=2&email=3&phone=4&address=5'
                }
            fetch(url,options)
            .then((res)=>{
                return res.json()
            })
            .then((res)=>{
                console.log(res)
            })

第二种方式

 componentDidMount(){
            var data = {
                name:"1",
                sex:"2",
                email:"3",
                phone:"4",
                address:"5"
            }
            fetch('http://127.0.0.1:8899/api/insertData',{
                method: 'POST',
                body: `data=${JSON.stringify(data)}`,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                  }
            })
            .then((res)=>{
                console.log(res.json())
            })
        }

Content-Type: 上传文件的时候,一定要设置为application/x-www-form-urlencoded


跨域

fetch跨域概述

在fetch跨域配置中有mode选项,提供了跨域的能力

  • mode: 'cors', // no-cors, cors, *same-origin
  • mode:'cors'

    • 这个选项提供了跨域的能力, 但是服务端必须支持 cors ,也就是设置 res.header("Access-Control-Allow-Origin", "*");
  • mode:'no-cors'

    • 可以跨域进行数据请求 , 不需要设置跨域 header
    • 在该模式下 得到的返回数据中 type为opaque。, 能够在控制台看到返回的数据, 但是没有权限使用这些数据
  • mode:"same-origin"

    • 同源, 不允许跨域

并不能成功跨域进行数据的请求

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Hello World</title>
        <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script crossorigin src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
        <!--数据请求-->
        <script src="https://cdn.bootcss.com/fetch/2.0.3/fetch.min.js"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>
<script type="text/babel">
    class Fetch_get extends React.Component{
        constructor(props){
            super(props)
            this.state = {
                arr:[]
            }
        }
        render(){
            return (
                <div>
                    <ul>
                        {
                            this.state.arr.map((ele,index,arr)=>{
                                return <li key={index}>{ele.name}</li>
                            })
                        }
                    </ul>
                </div>
            )
        }
        componentDidMount(){
             var url = "https://api.douban.com/v2/movie/top250"
            // var url = 'http://127.0.0.1:8899/api/selectData'
            var option = {
                methods:"get",
                mode:'no-cors'
            }
            fetch(url,option).then((res)=>{
                console.log(res)
            })
        }
    }
    ReactDOM.render(
        <Fetch_get></Fetch_get>, 
        document.getElementById('root') 
    );
</script>

使用jsonp调取数据

在原生js中,我们可以利用script标签的支持跨域的特性进行

第一种方式---利用script标签的跨域访问特性

 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>JSONP实现跨域2</title>
    </head>
    <body>
    </body>
    </html>
    <!--代码的先后顺序 不能变-->
    <script type="text/javascript">
        function fn(response){
                console.log(response);
        }
    </script>
    <script src="https://api.douban.com/v2/movie/top250?callback=fn"></script>

第二种方式---动态创建script

 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>JSONP实现跨域2</title>
    </head>
    <body>
    </body>
    </html>
    <!--代码的先后顺序 不能变-->
    <script type="text/javascript">
        function fn(response){
                console.log(response);
        }
        var script = document.createElement('script')
        script.src = 'https://api.douban.com/v2/movie/top250?callback=fn'
        document.body.insertBefore(script, document.body.firstChild);   
    </script>

第三种方式---使用jquery

  <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
        </head>
        <body>
        </body>
    </html>
    <script src="https://code.jquery.com/jquery.js"></script>
    <script type="text/javascript">
        $.ajax({
            type:'get',
            url:"https://api.douban.com/v2/movie/top250?callback=?",
            success(res){
                console.log(res)
            },
            dataType:"jsonp"
        })
    </script>

 类似资料: