我有一个Rails服务器,我正试图从React客户端发出获取请求。我想每次发表新评论时都能得到帖子的评论。
posts_controller.rb
# GET /post/1
# GET /post/1.json
def show
@post = Post.kept.friendly.find(params[:id])
@comments = @post.comments.kept.order(created_at: :desc)
end
我的React组件
useEffect(() => {
fetch('/posts/post-title')
.then((res) => {
console.log("res", res);
})
.catch((err) => {
console.log("err", err);
});
}, []);
结果
res Response {type: "basic", url: "http://localhost:3000/posts/post-title", redirected: false, status: 200, ok: true, …}
我打开了响应,但没有看到任何json注释。我试过做res.json()
,但我得到了undefined
。
我做错了什么?
将您的表演动作更改为此
def show
@post = Post.kept.friendly.find(params[:id])
@comments = @post.comments.kept.order(created_at: :desc)
render json: @comments
end
和你的JS到这个
useEffect(() => {
fetch('/posts/post-title')
.then(res => res.json())
.then((post) => {
console.log(post)
})
.catch((err) => {
console.log("err", err);
});
}, []);