0

I am trying to show data returned from MongoDB in my React app, but I am getting an error.

Here is my server.js file:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const BookModel = require("./models/book");

/// DATABASE CONNECTION
mongoose.connect(
  "mongodb://localhost:27017/excavate?readPreference=primary&appname=MongoDB%20Compass&ssl=false",
  { useNewUrlParser: true }
);

// app.get("/insert", async (req, res) => {
//   const friend = new FriendModel({ name: "Jessic", age: 38 });
//   await friend.save();
//   res.send("Inserted DATA");
// });

app.get("/read", async (req, res) => {
  BookModel.find({}, (err, result) => {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

app.listen(3001, () => {
  console.log("You are connected!");
});

Here is my App.js file in the client folder:

 const [books, setBooks] = useState([])
  const[searchTerm, setSearchTerm] = useState("")
  const[selectedNote, setNote] = useState()

  useEffect( ()=> {
    Axios.get('http://localhost:3001/read').then((response)=> {
      // setBooks(response.data)
      // console.log(books)
      console.log(response)
    }).catch(()=>{
      console.log("ERR")
    })
  }, [])

But when I launch my React app and open the console, I am seeing this error (see attached screenshot).

error

Does anyone have any idea why the data is not returned? When I type 'node server.js' command in the Terminal and open http://localhost:3001/read in the browser, I can see the data in the browser.

1 Answers1

0

You need to allow CORS to solve the issue You can find instructions to allow CORS in thus link3 https://stackoverflow.com/a/64641435/8622555

Deli
  • 55
  • 7