React使用fetch进行网络请求示例 - 姚丹的博客 - CSDN博客

版权声明:个人见解,希望大家看到有什么问题多多指教! https://blog.csdn.net/qq_34475058/article/details/84238108

我网络请求的接口为

请求测试地址:http://www.xn--7t0ay76a.xn--6qq986b3xl/requestdemo/login
请求方式:post
请求参数:  name:"admin",        pwd:"123456"
请求头: 'content-type': 'application/json'
请求成功返回值:{"flag":"200","message":"请求成功!","data":null}
请求失败返回值:{"flag":"401","message":"请求失败!","data":null}

我在React自定义组件中生命周期方法componentDidMount()中进行的网络请求

  1. 引进fetch
import fetch from 'dva/fetch';
  1. 在package中配置代理,用来解决跨域的问题
"proxy": "http://www.xn--7t0ay76a.xn--6qq986b3xl",
  1. 调用fetch进行网络请求
componentDidMount() {
        //请求的url
        const url="/requestdemo/login";
        //请求的参数
        const param={
            name:"admin",
            pwd:"123456"
        };
        //调用fetch
        fetch(url,{
            //请求方式
            method:'POST',
            //将请求的参数转成json
            body:JSON.stringify(param) ,
            //请求头
            headers: {
                'content-type': 'application/json'
            }
        // 请求的返回值
        }).then(function (response) {
            if(response.status===200){
                response.json().then(function (data) {
                    //获取请求的返回字段
                    console.log(data);
                    console.log(data.flag);
                    console.log(data.message);
                    console.log(data.data)
                })
            }else {
                alert("出现一个问题");
            }

        })
    }

Original url: Access
Created at: 2019-04-18 20:35:09
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论