node.js - 无法获取 /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');
}
});
解决方案
我的直接想法是api调用发生在root以外的页面上,在这种情况下是在/posts
页面中(又名http://your-site.com/posts)
通过在您调用前添加正斜杠将强制您的 api 请求从根开始。
尝试
await axios.get(`/api/posts/${id}`);
推荐阅读
- python - python - 如何从python列表中调用具有某些关键字的特定元素?
- c# - 在 C# 应用程序中使用 Azure REST API 显示没有响应
- python-3.6 - Python3 中的 Gauss-Seidel 方法,在每个周期开始时,为什么我必须将最近解决方案的数组设置为零?
- compilation - 如何清除对 Mix_MusicInterface_MPG123 的未定义引用?
- c# - 无需身份验证即可使用 Google Sheets API
- asp.net-core - 在 ASP.NET Core 中使用 JWT 承载添加声明
- github - 按全名对组织存储库进行排序时的 GitHub“错误网关”
- sql-server - 为什么查询时间如此不同?
- php - 它在 update.php 文件中显示其 ID,查询成功运行但未更新产品图像、名称和描述?
- sql - 选择同一ID的多条记录之间的日期差异