react+node 连接数据库报错--the server responded with a status of 500 (Internal Server Error)
import React from 'react'
import './index.scss'
import axios from 'axios';
class AddComments extends React.Component {
// 初始化状态
state = {
comments: [
{ id: 1, name: 'cnyangx', content: '前排出售瓜子、汽水、辣条!!!' },
{ id: 2, name: '大脸猫', content: '沙发~' },
{ id: 3, name: '老张', content: '我有酒,你有故事吗' }
],
userName: '',
userContent: ''
};
handleForm = (e) => {
this.setState({
[e.target.name]: e.target.value
})
};
// 验证id唯一性
verifyID = () => {
const newID = Math.floor(Math.random() * 100000);
const flag = this.state.comments.find(item => item.id === newID);
console.log(flag)
if (flag === -1) {
this.verifyID()
}
return newID;
};
// 发表评论
publishComments = async () => {
const { userName, userContent } = this.state;
if (userName.trim() === '' || userContent.trim() === '') {
alert('请输入内容');
return;
}
try {
await axios.post('/api/v1/user/comments', { userName, userContent });
// 成功后,你可以刷新评论列表,或者添加评论到本地状态,这里仅演示API调用
alert('评论发表成功');
} catch (error) {
console.error('发表评论时出错:', error);
alert('评论发表失败,请重试');
}
};
renderList = () => {
return this.state.comments.length === 0 ?
(<div className="no-comments">暂无评论,快去抢沙发吧!</div>) :
(
<ul>
{
this.state.comments.map(item => (
<li key={item.id}>
<h4>评论人: {item.name}</h4>
<p>评论内容:{item.content}</p>
</li>
))
}
</ul>
)
};
render() {
const { userName, userContent } = this.state;
return (
<div className="app">
<div>
<input type="text"
name="userName"
value={userName}
onChange={this.handleForm}
className="user"
placeholder="请输入评论人" />
<br />
<textarea name="userContent"
className="content"
value={userContent}
onChange={this.handleForm}
cols="30" rows="10"
placeholder="请输入评论内容">
</textarea>
<br />
<button onClick={this.publishComments}>发表评论</button>
</div>
{/* 渲染评论列表 使用三元表达式 */}
{this.renderList()}
</div>
)
}
}
// 导出
export default AddComments;
