Search code examples
javascriptaxiosgetmern

Getting an "Network Error" when making HTTP requests from the server


I have been trying to connect my client to my server but for some reason when I tried to use axios.get(http://localhost:3000/api/v1/products), I am getting "Network error" but if I check on browser the endpoint, I can see the square brackets and this is what I got from my server's terminal GET /api/v1/products 304. Can anyone help to explain this to me as I am a newbie. Thank you!

useEffect(() => {
  const fetchPosts = async () => {
    try {
      const response = await axios.get(
        'http://localhost:3000/api/v1/products',
      );
      console.log('response: ', response);
    } catch (error) {
      console.log(`Client Error: ${error.message}`);
    }
  };
  fetchPosts();
}, []);

Server

const express = require("express");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const mongoose = require("mongoose");
var cors = require("cors");

require("dotenv/config");
const app = express();
app.use(cors());
app.options('*', cors());
app.use(bodyParser.json());
app.use(morgan("tiny"));

const productSchema = mongoose.Schema({
  name: String,
  image: String,
  countInStock: Number,
});

const Product = mongoose.model("Product", productSchema);

const api = process.env.API_URL;

app.get(`${api}/products`, async (req, res) => {
  const products = await Product.find();
  if (!products) return res.status(500).json({ success: false });
  res.send(products);
});

app.post(`${api}/products`, (req, res) => {
  const product = new Product({
    id: req.body.id,
    name: req.body.name,
    image: req.body.image,
  });
  product
    .save()
    .then((createdProduct) => {
      res.status(201).json(createdProduct);
    })
    .catch((error) => {
      res.status(500).json({
        error: error,
        successful: false,
      });
    });
});


mongoose
  .connect(process.env.CONNECTION_STRING, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    dbName: "Firebase101",
  })
  .then(() => {
    console.log("Database connection is ready!");
  })
  .catch((error) => {
    console.log(error);
  });

app.listen(3000, () => {
  console.log("Server is running now! http://localhost:3000");
});

Solution

  • Since I am new in react native, I have found out that the the localhost I used is working only for IOS. For android, I should have used this http://10.0.2.2:3000/api/v1/products