首页 > 解决方案 > 无法获取 /post/api/posts/5c804ec6ad029f21201c686e 未找到,因为不需要附加单词“posts”

问题描述

每当我尝试获取 post api 时,我都会收到错误提示无法获取 /posts/api/posts/5c804ec6ad029f21201c686e

我无法弄清楚在我使用 axios 的 api 调用中附加了“帖子”一词的位置。我检查了我的代码,但我无法捕捉到错误。谁能帮我解决这个问题。

Post.js ;-

import React, { Fragment, useEffect } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux';
import Spinner from '../layout/Spinner';
import { getPost } from '../../actions/post';
import PostItem from '../posts/PostItem';

const Post = ({ getPost, post: { post, loading }, match }) => {

    useEffect(() => {
        getPost(match.params.id)
    }, [getPost]);

    return <h1>Post</h1>

    // loading || post === null ? <Spinner /> :
    //     <Fragment>
    //         <PostItem post={post} showActions={false} />
    //     </Fragment>

}

Post.propTypes = {
    getPost: PropTypes.func.isRequired,
    post: PropTypes.object.isRequired,
}
const mapStateToProps = state => ({
    post: state.post
})

export default connect(mapStateToProps, { getPost })(Post)

发布操作:-

import axios from "axios";
import { setAlert } from './alert';
import {
    GET_POSTS,
    POST_ERROR,
    UPDATE_LIKES,
    DELETE_POST,
    ADD_POST,
    GET_POST
} from './types';

// Get post
export const getPost = id => async dispatch => {
    try {

        const res = await axios.get(`api/posts/${id}`);

        dispatch({
            type: GET_POST,
            payload: res.data
        })

    } catch (err) {

        dispatch({
            type: POST_ERROR,
            payload: { msg: err.response.statusText, status: err.response.status }
        })

    }
}

Node.js 中的后端代码

//@route  Get api/posts/:id
//@desc   GET Post by Id
//@access Private

router.get("/:id", auth, async (req, res) => {
    try {
        const post = await Post.findById(req.params.id);

        if (!post) {
            return res.status(404).json({ msg: 'Post not found' })
        }
        res.json(post);
    } catch (err) {
        console.log(err.message);
        if (err.kind === 'ObjectId') {
            return res.status(404).json({ msg: 'Post not found' })
        }
        res.status(500).send('Server Error');
    }

});

标签: node.jsreact-redux

解决方案


我的直接想法是api调用发生在root以外的页面上,在这种情况下是在/posts页面中(又名http://your-site.com/posts

通过在您调用前添加正斜杠将强制您的 api 请求从根开始。

尝试

await axios.get(`/api/posts/${id}`);

推荐阅读