Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native fetch returns error: JSON Unexpected EOF

I hope someone here can help shred some light on the issue for me. I have been fighting this one error for too long now.

I am making a fetch request to an API for a sensor, which results in the same error all the time: JSON Parse error: Unexpected EOF

I have tried to find an answer online and attempted a lot of suggestions, but none of them worked.

In the development environment, I am accessing the API over a local network.

fetchUsers(timer) {
    let data = {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer ' + this.state.token.access_token
        }
    }
    fetch('http://' + this.state.ip + ':5000/api/Devices/031.01.0657/LiveState', data)
        .then(response => response.json())
        .then(responseJson => {
            this.setState({
                isLoading: false,
                error: false,
                userDataSource: responseJson,
                refreshing: false,
                time: timer
            }, function () {
                // If success, do something (I never make it to this part)
            });
        })
        .catch(error => {
            this.setState({
                isLoading: false,
                error: true
            })
            console.error(error);
        });
}

I have of course been using other means to see what the API returns:

The JSON I get in response when using the API interface:

{
    "device": null,
    "patient": null
}

The JSON I get in response when using the Postman client:

{
    "device": null,
    "patient": null
}

Using the exact same URL as in the code. The returned JSON also passes as valid JSON.

like image 471
André Gollubits Avatar asked Nov 22 '17 15:11

André Gollubits


2 Answers

I suppose that it fails on this line: response.json(). You can see what the response has before trying to convert it:

.then(response => {
    console.log(JSON.stringify(response, null, 4))
    return response.json())
}

I'm not sure about the

null

values in your JSON. I think you should use

"null"

Hope it helps you!

like image 86
Hernán Albertario Avatar answered Sep 18 '22 20:09

Hernán Albertario


Just catch the error at the line is being thrown so that it. The problem is response.json is null

try {
  responseData = await response.json();
} catch (e) {
    dispatch({ type: XXX_SSSSS, service: null });
}
like image 23
Odeyinka Olubunmi Avatar answered Sep 19 '22 20:09

Odeyinka Olubunmi