Home > Mobile >  How to retrieve boolean returned from nodejs/express at React Native front end?
How to retrieve boolean returned from nodejs/express at React Native front end?

Time:04-04

In my nodejs project, here is the code on both server and React Native front end:

server:

router.get("/api/path", (req, res) => {
  //do something
  return res.status(200).send(response);  //response is json object by default
})

front end:

let url  = `http://server/api/path`;
let res = fetch(url);
let result = await res.json();

If the server response is a boolean:

router.get("/api/path", (req, res) => {
      //do something
      return res.status(200).send(boolean);  //true or false
    })

How to retrieve this boolean at React Native front end?

CodePudding user response:

Nice question and I had to sweat a bit to try this out but I managed to set up a nice example. The answer is, to use the res.text() instead of json().

Here is my express API:

https://codesandbox.io/s/express-js-forked-p3grxc?file=/src/index.js

Here is the React app using it.

https://codesandbox.io/s/fetch-example-forked-yiyt3e?file=/src/index.js

The type of return may not be what you expect, but you get the value as an object.

  • Related