Home > front end >  Cannot fetch data from Nodejs backend to React frontend
Cannot fetch data from Nodejs backend to React frontend

Time:08-12

I'm building MERN stack CRUD with goolge login

I'm running my server on port:3001 and frontend on port:3000

  getAll() {
    return axios.get("http://localhost:3001/jobs")
  }

try to fetch data with session loggedin

router.get("/", util.isLoggedin, (req, res) => {
  Job.find()
    // .populate("author")
    .limit(20)
    .sort({ jobId: -1 })
    .then((jobs) => res.json(jobs))
    .catch((err) => res.status(400).json("Error:"   err))
})
const util = {}

util.isLoggedin = function (req, res, next) {
  console.log(req.isAuthenticated())
  if (req.isAuthenticated()) {
    next()
  } else {
    console.log(req.isAuthenticated())
    res.redirect("/")
  }
}

module.exports = util

I can retrieve the data only on the server side, not frontend. what can be the solution?

source code: https://github.com/jamespark89/mern-communitywebsite

CodePudding user response:

it seems like you are not awaiting your promise..

async getAll() {
    return await axios.get("http://localhost:3001/jobs")
  }

CodePudding user response:

replace

getAll() {
   return axios.get("http://localhost:3001/jobs")
}

with

async getAll() {
  return await axios.get("http://localhost:3001/jobs")
}

CodePudding user response:

Try to make your get request as an async function I usualy do that:

router.get("/", util.isLoggedin, async (req, res) => {
   try {
     const res = await Job.find()
     // .populate("author")
    .limit(20)
    .sort({ jobId: -1 })
    res.status(400).json({ res })
   } catch(err) {
     res.status(400).json("Error:"   err)
   }
})
  • Related