Commit 2cb2f704 authored by IronHammer Std's avatar IronHammer Std
Browse files

添加跑通了

parent 902cb884
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>
</>
)
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment