首页 > 解决方案 > axios.get() 没有在客户端获取数据

问题描述

我一直在尝试为我的社交媒体应用程序实现一个 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)
        }
    }

喜欢.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)

喜欢.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

标签: node.jsreactjsexpressaxiosget

解决方案


感谢@cmgchess 让我思考我使用请求正文发出“GET”请求的方法。

我将正文参数更改为查询参数,它确实有效:)

改变了Like.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 () => {
            
            // ---- DIFF OPEN ----
            const search = `?postId=${postId}&reactionType=${LIKE}`

            const likeRes = await axios.get(`/reactions${search}`)
            // ---- DIFF CLOSE ----

            console.log("Like res data", likeRes.data) // The logged array has data :)
            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)
        }
    }

改变了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
// --- DIFF OPEN ---
router.get("/", async (req, res) => {
    const postId = req.query.postId
    const reactionType = req.query.reactionType
    try {
        const reactions = await Reaction.find({
            postId,
            reactionType
        })
// --- DIFF CLOSE ---
        res.status(200).json(reactions)
    } catch(err) {
        res.status(500).json(err)
    }
})

module.exports = router


推荐阅读