【发布时间】:2021-01-22 05:31:52
【问题描述】:
我正在为我的网站创建一个评论部分,在我的前端,我想创建一个函数来显示用户在数据库中发布的评论。
但是当我创建了一个检索评论并显示它的函数时,评论不会显示出来。我不知道我做错了什么,是我放错了地方还是我编程正确?
这是我的后端程序
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>
)
}
【问题讨论】:
-
为什么是
document.getElementById("comment-section").innerHTML = response? -
然后在 api 调用类似这样的
.then((response) => response.json()) -
你为什么要这样使用
const [comment, inputComment] = useState ('')的useState,你应该这样使用const [comment, setcomment] = useState ('')
标签: javascript mysql reactjs express axios