在发出post请求时获得此错误(API在没有发送/ API /comments响应的情况下进行解析,这可能导致请求停滞)



您好,我已经开始学习Next.js,目前无法在api上发出POST请求。

我在api文件夹中有一个注释文件夹。在注释中,我写了这样的代码:


import { comments } from "../../../data/comments";
export default function handler(req,res) {

if(req.method === 'GET'){
res.status(200).json(comments)
}
else if(req.mehtod === 'POST') {
const data = req.body.comment
const newComment = {
id: Date.now(),
data
}
comments.push(newComment)
console.log(comments);
res.status(201).json(newComment)
}
}

这里的导入注释只是一个简单的Js文件,我返回一个数组。

在前端部分部分,我有一个页面,我有一个输入和一个按钮,并在点击按钮,我调用submitCommentHandler。

在submitcommentHandler中,我尝试通过fetch和axios到达路径。但在这两种情况下,我得到一个消息

没有发送/API/comments响应的API解析,这可能导致请求停滞。


import { useState } from "react"
import axios from "axios"
const Comments = () => {
const [comments, setComments] = useState([])
const [comment, setComment] = useState('')
const clickHandler = async () => {
// const response = await fetch("/api/comments")
// const data = await response.json()
axios.get('/api/comments')
.then(response => {
setComments(response.data);
})
.catch(error => {
console.log(error);
})


}
// const submitCommentHandler = async (e) => {
//     e.preventDefault();
//     console.log(comment);
//     // axios.post("api/comments", {comment})
//     //   .then(response => console.log(response))
//     //   .catch(error => console.log(error))
//     const response = await fetch('http://localhost:3000/api/comments', {
//         method: 'POST',
//         headers: {
//             'Content-Type': 'application/json'
//         },
//         comment
//     })
// }
const submitCommentHandler = async () => {
const response = await fetch('/api/comments', {
method: 'POST',
body: JSON.stringify({comment}),
headers: {
'Content-Type': 'application/json',
},
})
const data = await response.json()
console.log(data);
}
return ( 
<div className="container">
<div className="submit-comments-container">
<input value={comment} onChange={e => setComment(e.target.value)}></input>
<button onClick={submitCommentHandler}>Submit Comment</button>
</div>
<div className="btn-container">
<button onClick={clickHandler}>Show Comments</button>
</div>
<div className="comments-container">
{
comments.map(comment => {
return (
<div className="comment-container" key={comment.id}>
<h1>{comment.id}</h1>{' '}
<h1>{comment.data}</h1>
<hr/>
</div>
)
})
}
</div>
</div>
);
}

export default Comments;

你的API似乎是好的,只是纠正拼写的req。方法=== 'POST'在else if条件下,然后通过npm命令运行应用程序,然后刷新浏览器,这样你可能不会收到警告。

最新更新