简体   繁体   中英

Cannot fetch data from Nodejs backend to React frontend

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

it seems like you are not awaiting your promise..

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

replace

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

with

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM