0
votes

I use Axios in my react native app. I use Mobiistar Zumbo J2 with Expo to test but I get err: Network Error. I also set CORS for my node server but it still doesn't work. I test with Postman it work normally. Here is my code:


server.js

const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");

const index = require("./routes/index");
const bookings = require("./routes/bookings");
const cors = require('cors'); // Yep, you need to install this

const app = express();
const port = process.env.PORT || 3000;

app.use(cors());

app.listen(port, () => {
    console.log('Server is running on port', port);
});

app.set("views", path.join(__dirname, "views"));
app.set("view engine", 'ejs');
app.engine("html", require("ejs").renderFile);
//Body parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

//Routes
app.use("/", index);
app.use("/api", bookings);

bookings.js

const express = require("express");
const router = express.Router();
const mongojs = require("mongojs");

const db = mongojs("mongodb://<username>:<password>@ds139614.mlab.com:39614/booking-car-app", ["bookings"]);

router.get("/bookings", (req, res, next) => {
    db.bookings.find((err, data) => {
        if (err) {
            res.send(err);
        }
        res.json(data);
    });
});

router.post("/bookings", (req, res, next) => {
    const booking = req.body;

    if (!booking.userName) {
        res.status(400);
        res.json({err: "Bad data"});
    } else {
        db.bookings.save(booking, (err, savedBooking) => {
            if (err) {
                res.send(err);
            }
            res.json(savedBooking);
        })
    }
})

module.exports = router;

using Axios to get data from server

axios.get("http://127.0.0.1:3000/api/bookings/")
  .then(res => {
      console.log("Get booking info: ", res);
      alert(res);

  })
  .catch(err => console.log(err))

Error:

Network Error

Stack trace:
  node_modules\axios\lib\core\createError.js:16:24 in createError
  node_modules\axios\lib\adapters\xhr.js:87:25 in handleError
  node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
  node_modules\react-native\Libraries\Network\XMLHttpRequest.js:578:29 in setReadyState
  node_modules\react-native\Libraries\Network\XMLHttpRequest.js:392:25 in __didCompleteResponse
  node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:191:12 in emit
  node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349:47 in __callFunction
  node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106:26 in <unknown>
  node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297:10 in __guard
  node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105:17 in callFunctionReturnFlushedQueue
  ...

Please help me. Thank you very much
1
add "0.0.0.0", as second parameter to your app.listen and also put your app.listen at the end of file - moein rahimi
Thank you for you answer, but I found the reason. I used wrong base url (127.0.0.1:3000). I test my app in my android phone and develop in my laptop, they are connected to the same wifi network so base url of axios have to be the ip of the wifi network. - Michael

1 Answers

0
votes

Android uses a special type of IP address 10.0.2.2

axios.get("http://10.0.2.2:3000//api/bookings/")
  .then(res => {
     console.log("Get booking info: ", res);
     alert(res);

  })
  .catch(err => console.log(err))