[英]Cannot fetch data from Nodejs backend to React frontend
我正在使用 goolge 登錄構建 MERN 堆棧 CRUD
我在端口:3001 上運行我的服務器,在端口:3000 上運行前端
getAll() {
return axios.get("http://localhost:3001/jobs")
}
嘗試使用登錄的 session 獲取數據
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
我只能在服務器端檢索數據,而不是前端。 有什么解決辦法?
看來您並沒有在等待您的 promise..
async getAll() {
return await axios.get("http://localhost:3001/jobs")
}
代替
getAll() {
return axios.get("http://localhost:3001/jobs")
}
和
async getAll() {
return await axios.get("http://localhost:3001/jobs")
}
嘗試將您的獲取請求作為異步 function 我通常這樣做:
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)
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.