react用fetch获取接口数据,文件上传等

本文主要介绍了在React应用中如何利用fetch API获取JSON数据、发送请求、登录参数提交以及文件上传。首先展示了一个fetch获取JSON数据的例子,并详细解释了fetch的相关方法。此外,还提到了在处理事件时阻止事件冒泡和阻止默认行为的方法。

一 : React使用fetch获取json数据

先写个例子,再详细说明fetch

pageTest2.json

{
    "code": "1",
    "msg": "查询成功",
    "arr":[{
		"key":"001",
		"idd":"001",
		"title":"react版本更新1",
		"time":"2018-12-01",
		"contents":"66666666666666!"
	},{
		"key":"002",
		"idd":"002",
		"title":"react版本更新2",
		"time":"2018-12-01",
		"contents":"66666666666666!"
	},{
		"key":"003",
		"idd":"003",
		"title":"react版本更新3",
		"time":"2018-12-01",
		"contents":"66666666666666!"
	}]

}

react:

import React, { Component } from 'react';

class Page extends Component {
    constructor(props){
        super(props);
        this.state = {
            totalData:[]
        };

    }
  
    getData(){  //请求数据函数
        fetch('/api/pageTest2.json')   
             //这里json放在了本地,可以直接换成在线接口"http://www.某某/robot/getUsers"
            .then(response => response.json())  ///解析json数据
            .then(data => {
                console.log(data)
                this.setState({totalData: data.arr})  ////赋值到本地数据
                console.log(this.state.totalData)

            })
            .catch(e => console.log('错误:', e))   ///请求出错
    }

    componentDidMount() {//网络请求都是放在此生命周期函数中
        this.getData()
    }
   
    render() {

        return (
            <div className="main">
                
             { 
                 this.state.totalData.map((item,index)=>{
                    return <p key={index}>{item.title}</p>
                })
              }
            
            </div>
        );
    }
}

export default Page;

fetch一些方法详解

fetch('/api/pageTest2.json',{
       method: "GET", // 请求的方法POST/GET等 
       headers: {  // 请求头(可以是Headers对象,也可是JSON对象)
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
       body: , // 请求发送的数据(get或head方法中不能包含body)
       cache : 'default', // 是否缓存这个请求
       credentials : 'same-origin', 
       //要不要携带 cookie 默认不携带 omit、same-origin 或者 include
       mode : ""

       //mode,给请求定义一个模式确保请求有效
       //same-origin:只在请求同域中资源时成功,其他请求将被拒绝(同源策略)
       //cors : 允许请求同域及返回CORS响应头的域中的资源,通常用作跨域请求来从第三方提供的API获取数据
       //cors-with-forced-preflight:在发出实际请求前执行preflight检查
       //no-cors : 目前不起作用(默认)

}).then(response => response.json())  ///解析json数据
  .then(data => {
                console.log(data)
                this.setState({totalData: data.arr})  ////赋值到本地数据
                console.log(this.state.totalData)

            })
   .catch(e => console.log('错误:', e))   ///请求出错

 经常用到的一些情况

1.请求json数据时

 fetch('/api/pageTest2.json')   
            .then(response => response.json())  ///解析json数据
            .then(data => {
                console.log(data)
            })
            .catch(e => console.log('错误:', e))   ///请求出错

2.请求文本

fetch('/api/word')   
            .then(response => response.text())  ///解析文本
            .then(data => {
                console.log(data)
            })
            .catch(e => console.log('错误:', e))   ///请求出错

3.发送json数据

fetch('/api/xxx',{
        method: 'post',
        body: JSON.stringify({
            username: '',
            password: ''
        })
    })   
    .then(response => response.json())  
    .catch(e => console.log('错误:', e))   ///出错

4.fetch 登录请求用formData提交参数

let url = "/api/xxx";//接口地址
 
let formData = new FormData();
formData.append('c','login');
formData.append('username', this.state.userName);
formData.append('password', this.state.passWord);
formData.append('client', 'android');
 
fetch(url,{
    method: 'post',
    body: formData,
}).then(response => response.json())  
  .then(data => {
              if (data.code == "200") {
                  console.log("正确")
                  console.log(data)
              }else if (data.code == "400") {
                  console.log("出错")
              }
                
            })
  

5.使用fetch上传文件

<input type="file" onChange={this.handleUpload}/>


handleUpload = (e) => {
	e.preventDefault();//阻止元素发生默认行为(例如,当点击提交按钮时阻止对表单的提交)
    
    let file = e.target.files[0];
    const formdata = new FormData();
    formdata.append('file', file);
        
    for (var value of formdata.values()) {
        console.log(value);
    }
    
    const url = '/file/upload';
    fetch(url, {
        method: 'POST',
        body: formdata
        /*headers: {
            "Content-Type": "multipart/form-data"
        }有它,POST请求会变成OPTIONS请求*/
    }).then(response => return response.json();)
      .catch(error => console.log(error));
};

延伸:

e.stopPropagation() 阻止事件冒泡

e.preventDefault() 阻止事件默认行为。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值