Search code examples
react-nativekoa

API returns 200 in postman but 404 in device


I have created a simple api using koa server and postgresql database for my application and tested it using postman and browser, works fine in both. Now I am trying to fetch data in my react native application (testing on actual device) but it is returning me this response:

{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "1bbc1ba3-a1b4-442e-ba85-d09d5d54f4e6", "offset": 0, "size": 9}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "1bbc1ba3-a1b4-442e-ba85-d09d5d54f4e6", "offset": 0, "size": 9}}, "headers": {"map": {"content-length": "9", "content-type": "text/plain; charset=utf-8", "date":
"Mon, 20 Apr 2020 12:26:12 GMT"}}, "ok": false, "status": 404, "statusText": undefined, "type": "default", "url":
"https://a1cd97c8.ngrok.io/posts/,function%20dispatchAction()%20%7B%20%20%20%20[native%20code]%7D"}

I am using ngrok URL mapping because without https my requests get straight up rejected.

Here is my code for request:

const searchURL = React.useState('https://a1cd97c8.ngrok.io/posts/');    
const fetchPosts = async () => {
        console.log('fetching');
        fetch(searchURL, {
          method: 'GET',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
        })
          .then((response) => {
            console.log('response: ', response);
            return response.json();
          })
          .then((json) => console.log('TESTOUTPUT', json))
          .catch((err) => console.log('error: ', err.message));
      };

The error message I get in catch block is:

error:  JSON Parse error: Unexpected identifier "Not"

What am I doing wrong?


Solution

  • useState hook return an array so you should destructure the result

    const [searchURL, setSearchURL] = React.useState('https://a1cd97c8.ngrok.io/posts/');