【发布时间】:2021-12-11 15:06:14
【问题描述】:
我一直在尝试为我的社交媒体应用程序实现一个 LIKE 系统,在客户端做出反应并在服务器端表达。我正在尝试使用“useEffect”中的“axios”获取当前的 LIKE 统计信息。但是,“GET”请求后返回的数据是一个空数组,而不是实际数据。数据正在保存到 mongoDB,可以使用“POSTMAN”获取,但无法从客户端获取。有什么修复吗?
点赞.jsx
// Client-side where LIKE stats are fetched
import axios from 'axios';
import { useContext, useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import { Context } from '../../context/Context';
import './reactions.css'
export default function Reactions() {
const LIKE = "LIKE"
const { user } = useContext(Context)
const location = useLocation()
const postId = location.pathname.split("/")[2]
const [likes, setLikes] = useState(0)
const [refresh, setRefresh] = useState(false)
useEffect(() => {
const fetchReactions = async () => {
const likeRes = await axios.get(`/reactions/all`, {
data: {
postId,
reactionType: LIKE
}
})
console.log("Like res data", likeRes.data) // The logged array is empty :(
setLikes(likeRes.data.length)
}
fetchReactions()
}, [postId, refresh])
const handleReact = async (reactionType) => {
const newReaction = {
reactionType,
username: user.username,
postId,
}
try {
const res = await axios.post("/reactions", newReaction)
console.log(res.data) // The logged object has data :)
setRefresh(!refresh)
} catch(err) {
console.log(err)
}
}
Like.js
// Reaction model at server-side
const mongoose = require("mongoose")
const ReactionSchema = new mongoose.Schema(
{
reactionType: {
type: String,
required: true,
},
username: {
type: String,
required: true,
},
postId: {
type: String,
required: true,
}
},
{
timestamps: true,
}
)
module.exports = mongoose.model("Reaction", ReactionSchema)
likes.js
// API for creating and fetching LIKES
const router = require("express").Router()
const Reaction = require("../models/Reaction")
// CREATE REACTION
router.post("/", async (req, res) => {
const newReaction = new Reaction(req.body)
try {
const savedReaction = await newReaction.save()
res.status(200).json(savedReaction)
} catch(err) {
res.status(500).json(err)
}
})
// GET REACTIONS OF A POST
router.get("/all", async (req, res) => {
try {
const reactions = await Reaction.find({
postId: req.body.postId,
reactionType: req.body.reactionType,
})
res.status(200).json(reactions)
} catch(err) {
res.status(500).json(err)
}
})
module.exports = router
【问题讨论】:
-
你有添加拦截器吗?基本网址在哪里?
-
您是否也在使用正文数据发出获取请求
-
@Bassam,基本 URL 是“localhost:5000/api/reactions”。而且我不认为,它访问 URL 的方式没有问题,因为评论系统、帖子系统都以相同的方式访问 API,除了这里,get 是用 req.body 调用的。此外,可以使用 Postman 毫无问题地获取数据。
-
@cmgchess,是的。获取请求是使用 req.body 发出的,因为获取条件是作为 req.body 传递的。
标签: node.js reactjs express axios get