简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM