I am doing a fetch in React Native and am very new to React Native, by the way.
const apiUrl = 'http://hermes.hstn.me/api/';
const response = await fetch(apiUrl, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
if(!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const responseData = await response.json();
console.log('responseData: ', responseData);
You can visit the apiURL in the above code block and see the returned JSON content if you wish, but here it is:
{"status":"success","message":"data retrieved successfully","items":[{"id":1,"name":"a"},{"id":2,"name":"b"}]}
And here is the PHP code generating that JSON response:
<?php
$data = [
'status' => 'success',
'message' => 'data retrieved successfully',
'items' => [
['id' => 1, 'name' => 'a'],
['id' => 2, 'name' => 'b']
]
];
$jsonOutput = json_encode($data);
header('Content-Type: application/json');
echo $jsonOutput;
exit();
?>
And here is the error coming back in the ReactNative debug console:
Error: Uncaught (in promise, id: 0): "SyntaxError: JSON Parse error: Unexpected character: <"
at onUnhandled (promiseRejectionTrackingOptions.js:40:16)
at onUnhandled (address at InternalBytecode.js:1:3386)
Caused by: SyntaxError: JSON Parse error: Unexpected character: <
at parse (native)
at tryCallOne (address at InternalBytecode.js:1:1180)
at anonymous (address at InternalBytecode.js:1:1874)
I can not figure out where the unexpected character, <, is coming from in the error.
This is the first time I've worked in React Native. Have plenty of experience with Angular and never ran into this. So I'm guessing it's some quirk of what php is returning (headers somewhere maybe?) and React Native being extra strict?
<means you're getting an HTML response. It looks like there's some sort of redirect going on. When I use curl with a browser's user agent, I'm getting HTML. When I use curl with no user agent, or a fake one, I'm getting an empty response from the server.http://hermes.hstn.me/api/has headercontent-type: text/html; charset=UTF-8not asapplication/jsonin your PHP code. I guess React Native client API try to reconstruct response body followcontent-type header.