Search code examples
androidreactjsreact-nativefetchmultipartform-data

React Native android FormData response goes to catch block after .json()


I'm trying to POST data with FormData to get a response, on iOS it works as expected, but on android, it always goes to the catch block, I found out the reason for that is response.json() with error: [SyntaxError: JSON Parse error: Unrecognized token '']

Here is my code:

const onAndroidSucks = () => {
        setLoading(true);
        let formData = new FormData();

        formData.append("number", number.replace(/\s+/g, '').substring(4));
        formData.append("id", userID);
        formData.append("token", userToken);

        fetch(ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            body: formData
        }).then(response => response.json()).then(response => {
            if (response.res === 'no') {
                Alert.alert('ჰეჰე');
            } else {
                setData(response);
            }
            setLoading(false);
        }).catch(err => { Alert.alert(err.message); setLoading(false); } );
    };

I don't understand what the actual problem is here.


Solution

  • It turned out that problem was okHttp on android. Looks like okHttp appends an empty string " " without a known reason.

    Here is how I solved that issue with the workaround:

    }).then(response => response.text())
    .then((res) => JSON.parse(res.trim())).then(response => {