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'
    }
});
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章