Не могу использовать axios для получения / публикации данных с / на сервер localhost на устройстве Android 7.0 - React Native app - PullRequest
0 голосов
/ 22 декабря 2018

Я использую Axios в своем собственном приложении.Я использую Mobiistar Zumbo J2 с Expo для тестирования, но получаю ошибку: Ошибка сети.Я также установил CORS для моего сервера узлов, но он все еще не работает.Я тестирую с почтальоном это работает нормально.Вот мой код:


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;

с использованием Axios для получения данных с сервера

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))

Ошибка:

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
  ...
Пожалуйста, помогите мне.Большое спасибо
...