react native 出现 multipart !=application/json错误和IOS调试频繁出现TypeError network request failed错误解决办法

react native 端参考代码:

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    TouchableHighlight,
    Alert,
    TouchableOpacity,
    View
} from 'react-native';


//Post方法, 需要请求体body
/*
* FromData
* 主要用于序列化表单以及创建与表单格式相同的数据
*
* var data = new FormData();
* data.append("name","hello");
* append方法接收两个参数,键和值(key,value),分别表示表单字段的名字 和 字段的值,可添加多个
*
* 在jQuery中,"key1=value1&key2=valu2" 作为参数传入对象框架,会自动分装成FormData形式
* 在Fetch 中,进行post进行post请求,需要自动创建FormData对象传给body
*
* */
function postRequest(url) {
    //将"key1=value1&key2=valu2" 形式封装整FromData形式
    let formData = new FormData();
    formData.append("id","15");
    formData.append("verName","1111aaaa");

    var opts = {
        method:"POST",   //请求方法
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body:formData,   //请求体
    };


   fetch(url , {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',//改为 'Content-Type': 'multipart/form-data'即可解决


        },
        body: formData,
    }).then((response) => {
        if (response.ok) {
            return response.json();
        }
    }).then((json) => {
        console.log(json);
        console.log(json.id);
       console.log(json.verName);
        alert(JSON.stringify(json));
    }).catch((error) => {
        console.error(error);
    })
}


export default class HomeScreen extends Component {
    render() {
        return(
            <View style={styles.container}>
                {/*注意: 方法调用方式,绑定了this */}
                <TouchableOpacity onPress={postRequest.bind(this,"http://jmbsjk.com/test/test2.php")}>
                    <View style={styles.btn}>
                        <Text>Post</Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }
}

var styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'cyan',
        marginTop:30,
        flexDirection:'row',
        justifyContent:'center',
        alignItems:'center'
    },
    btn:{
        width:60,
        height:30,
        borderWidth:1,
        borderColor:"yellow",
        justifyContent:'center',
        alignItems:'center'
    }
});
 

发布了38 篇原创文章 · 获赞 10 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/winux123/article/details/89456388
今日推荐