实现 GET 请求时收到 404 状态 - MERN Stack

时间:2021-07-02 17:26:08

标签: node.js reactjs mongodb express axios

我正在尝试显示群组列表中的特定群组详细信息页面。我已经设法从后端显示所有组列表,但是在显示每个组详细信息页面时,我收到 404 的状态。我不明白问题是什么,为什么找不到对该特定 ID 进行分组。

在后端,我做了一个 getGroup 控制器:

export const getGroup = async (req, res) => {
    // Route parameters are named URL segments that are used to capture the values specified at their position in the URL.
    // Deconstructing it so that we can use it. It's like unpacking it.
    const { id } = req.params

    try {
        // finding a group by it's Id
        const group = await Group.findById(id)
        // Send it in response
        res.status(200).json(group)

    } catch (error) {
        // In case it didn't work out
        res.status(404).json({ message: error.message })
    }
}

然后路由:

router.get('/:id', getGroup)

主要路线:

app.use('/groups', groupRoutes)

在前端,我使用 Axios 创建 API。

export const fetchGroup = (id) => API.get(`/groups/${id}`)

使用 Redux 进行状态管理,所以这是我针对特定组的操作创建器。

// Will get a particular group
export const getGroup = (id) => async (dispatch) => {

    try {
        // Over here we are fetching all the data from api and dispatching it.
        const { data } = await api.fetchGroup(id)

        dispatch({type: FETCH_GROUP, payload: data})

    } catch (error) {
        console.log(error.message)
    }
}

用于获取组的减速器:

// Reducers take state and an action as arguments and return a new state in result.
const groups = ( state = { groups: [] }, action ) => {
    switch (action.type) {
        case FETCH_ALL:
            return {
                ...state,
                groups: action.payload 
            }
        case FETCH_GROUP:
            // set to group because we are getting a single group
            return { ...state, group: action.payload } 
        default:
            return state
    }
}

export default groups

我的 GroupPage.js,我在其中调度我的函数。

const GroupPage = () => {

    const { group } = useSelector((state) => state.groups)

    const dispatch = useDispatch()
    const { id } = useParams()
    
    useEffect(()=> {
        dispatch(getGroup(id))
    }, [id])
    
    //if(!group) return null

    return (
        isLoading ? <div style={{width: 50, height: 50 }}>
        <CircularProgressbar value={66} text={66} />
    </div> : (
        <div>
           <Container>
                <Top>
                    <div>
                        <h1>{group.groupName}</h1>
                        <p>{group.location}</p>
                        <p>{group.members}</p>
                    </div>
                </Top>
            </Container>
        </div>
    )
  )
}

export default GroupPage

从上面的代码,如果我检查一个组: if(!group) return null 然后我收到错误 typeError: Cannot read property 'groupName' of undefined

不知道是什么问题。我也尝试过在加载状态下获取数据,但这也没有解决问题。 请提供任何帮助,我们将不胜感激。

enter image description here

0 个答案:

没有答案