Commits (2)
......@@ -2,12 +2,11 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<meta name="viewport" content="width=device-width" />
<title>聊天区</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
</html>
\ No newline at end of file
import { useState } from 'react'
import './App.css'
const BackEndUrl : string = 'http://localhost:8080'
interface CommentData {
name: string
content: string
}
function App() {
const [username, setUsername] = useState<string>('')
const [comment, setComment] = useState<string>('')
const [error, setError] = useState<string>('')
const clearForm = () => {
setUsername('')
setComment('')
setError('')
}
const handleSubmit = async (e: React.FormEvent) => {
//无需检查是否为空,有required属性
//消除默认的表单提交行为
e.preventDefault()
// 清除之前的错误信息
setError('')
// 构造评论结构
const Comment : CommentData = {
name: username,
content: comment
}
try {
const response : Response = await fetch(BackEndUrl + '/comment/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(Comment),
})
//输出responce 的详细信息到控制台
console.log('Response Status:', response.status);
console.log('Response Headers:', response.headers);
console.log('Response URL:', response.url);
console.log('Response Body:', await response.text());
if (!response.ok) {
throw new Error('无法提交评论,错误码:' + response.status)
}
clearForm()
alert('提交成功!');
} catch (err) {
// 处理错误
console.error('提交失败:', err)
setError('提交失败:' + (err instanceof Error ? err.message : '未知错误'))
alert(error);
return
}
}
return(
<>
<h1>hello world!</h1>
<div className="submit-container">
<h3>user name</h3>
<form id="todoForm" onSubmit={handleSubmit}>
<input
type="text"
id="username"
name="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
></input>
<h3>comment content</h3>
<input
type="text"
id="comment"
name="comment"
value={comment}
onChange={(e) => setComment(e.target.value)}
required
></input>
<div>
<button type="submit">提交</button>
</div>
</form>
</div>
</>
)
}
......