Skip to content
GitLab
Projects
Groups
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
何 广一
intern_project_frontend
Commits
2cb2f704
Commit
2cb2f704
authored
Jun 23, 2025
by
IronHammer Std
Browse files
添加跑通了
parent
902cb884
Changes
1
Hide whitespace changes
Inline
Side-by-side
src/App.tsx
View file @
2cb2f704
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
>
</>
)
}
...
...
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment