这是我的代码 // 客户端逻辑
React.useEffect(() => {
const getComments = async () => {
try {
const response = await axios.get(
"http://localhost:3000/api/blog/comment/get-comments"
);
console.log(response.data);
if (!response.data.success) {
toast.error(response.data.message);
}
if (response.data.success) {
const comments = response.data.comments;
setBlogComments([...comments]);
}
} catch (error) {
console.log(error);
}
};
getComments();
}, []);
// API
import dbConnect from "@/lib/dbConnect";
import Comment from "@/models/CommentModel";
import { NextResponse } from "next/server";
export async function GET(request) {
dbConnect();
try {
const comments = await Comment.find({})
.populate("author")
.populate("blog")
.exec();
if (!comments) {
return NextResponse.json({
success: false,
message: "unable to fetch comments",
});
}
return NextResponse.json({
success: true,
comments: comments,
});
} catch (error) {
console.log(error);
return NextResponse.json({
success: false,
message: "Unable to get Comments",
});
}
}
我遇到的错误
GET http://localhost:3000/api/blog/comment/get-comments 405(不允许的方法)
我想获取评论,因此使用 get 我检查了语法和网址,我点击了所有内容,但它仍然不起作用!!
您遇到的错误,
405 Method Not Allowed
,通常表示您尝试访问的 API 路由未设置为处理您正在使用的 HTTP 方法(在本例中为 GET)。
这必须是您的 API 文件夹: // app/api/blog/comment/get-comments/route.js
await dbConnect(); // Ensure to await the db connection in API
调试技巧:
通过导航到浏览器中的
http://localhost:3000/api/blog/comment/get-comments
手动检查 API 路由。您应该会看到 JSON 响应。