我正在为我的网站创建一个评论部分,并且在我的前端,我想创建一个函数来显示用户在数据库中发布的评论。
但是当我创建一个检索评论并显示它的函数时,评论不会显示出来。我不知道我做错了什么,是我把它放错了地方还是我编程正确?
这是我的后端程序
app.post('/forum', function (req, res){
const queryString = "INSERT INTO comments (Comments) VALUES (?)"
console.log (req.body)
con.query(queryString, [req.body.comment], function (err, result){
if (err) {
throw err;
}
if (result.length != 1) {
return res.send("Posted Comment")
}
else {
res.send('Comment failed to post')
};
})
})
app.get('/forum', function (req, res){
const queryString = 'SELECT * FROM comments WHERE Comments = ?'
console.log (req.body)
con.query(queryString, [req.body.insert], function (err, result){
if (err) {throw err;}
var commenting = JSON.stringify(result)
res.send(commenting);
})
})
检索响应的 api 调用
static async forum(comm){
const response = await axios
.post('http://localhost:8080/forum', {
comment: comm,
})
.then ()
return response.data;
}
static async comment(comm){
const response = await axios
.get('http://localhost:8080/forum', {
comment: comm
})
.then ()
return response.data;
}
和我的前端,评论会出现
function Forum() {
const [comment, inputComment] = useState ('')
/*user posts the comment*/
const onPost = (event) => {
event.preventDefault()
apiClient.forum(comment) .then( (response) => {
console.log(response)
})
}
/*users comment gets displayed*/
apiClient.comment() .then((response) =>{
document.getElementById("comment-section").innerHTML = response
})
return (
<section class = "index-banner" >
<div>
<label>Comment</label>
<textarea name="comment" id= "comment" rows="10" tabIndex = "4"onChange = {e => {inputComment(e.target.value)}}></textarea>
<button onClick={onPost}>Post</button>
</div>
<div>
<body id = "comment-section" ></body>
</div>
</section>
)
}
答案 0 :(得分:0)
请求肯定会通过吗?您可以在浏览器 DevTools 的网络选项卡中进行验证。
我可以提出一些关于更好地使用 React 的建议。
document.getElementById
document.getElementById
useState
:function Forum() {
const [comment, setComment] = useState ('')
const [postedComment, setPostedComment] = useState ('')
const onPost = (event) => {
event.preventDefault()
apiClient
.forum(comment)
.then( (response) => {
console.log(response.data)
// this should trigger a rerender, in the <div>{postedComment}</div>
// assuming your response contains the posted comment:
setPostedComment(response.data)
})
.catch( error => console.log(error) /* handle Exception here */)
}
return <div>
<label>Comment</label>
<textarea
name="comment"
id="comment"
rows="10"
tabIndex ="4"
onChange={e => {inputComment(e.target.value)}}>
</textarea>
<button onClick={onPost}>Post</button>
<div>{ postedComment }</div>
</div>
}
useRef
: const commentRef = useRef(null)
// ...
const onPost = (event) => {
event.preventDefault()
apiClient
.forum(comment)
.then( (response) => {
console.log(response)
// assuming your response contains the posted comment:
commentRef.current.innerHTML = response
})
.catch( error => console.log(error) /* handle Exception here */)
}
return <div>
{/* ... */}
<div ref={commentRef}>
</div>
</div>
<块引用>
注意:
body
元素!解决一些评论: