javascriptexpressreact-nativeexpress-generator

How do you send a request to an express server from a react native app?


I have 2 separate apps, a react-native app and an express backend server. I created the server using express-generator. My server has the following code in users.js

router.get('/', function(req, res, next) {
  res.json([{
    id: 1,
    username: "foo"
  }, {
    id: 2,
    username: "bar"
  }]);
});

The server is set to listen on port 8080 and have app.use('/users', users). Basically, just all of the code that comes with express-generator.

In my react native app, I have: "proxy": "http://localhost:8080"

And then in App.js:

componentDidMount() {
  fetch('/users'
   .then(res => res.json())
   .then(users => this.setState({ users }))
}

I am using Expo to load my app on an Android device, and am getting: unexpected url: /users. If I visit localhost:8080 in my browser, the data is visible, so I think that the issue must be on the client side.


Solution

  • You need to add the complete hostname and port number when making a request. You need to write complete url when getting data as http://localhost:8080/users in your App.js.