当使用ReactJS单击按钮时,如何返回从REST API(ExpressJS)保存的JSON响应?



我试图使用fetch API将来自我的React前端应用程序的用户添加到我的休息API中。它确实将数据保存到数据库中。但是当我单击按钮时,我没有从 API 收到res.status(201).json({"user" : user})JSON 响应。我想要这样的回复:

{
"username": "Verginia",
"_id": "BkNjV359I"
}

这是我的表单按钮点击的 React 代码

async function handleClick(event) {
event.preventDefault()
const body = { username }
let response 
try {
response = await fetch('http://localhost:5000/api/users', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body)
})
} catch (error) {
console.log(error.message)
}
console.log(response)
}

这是我的表单代码(我将按钮和输入作为单独的组件

<form className="d-flex">
<Input 
className="form-control" 
type="text" 
name="username"
value={username}
placeholder="Enter Username"  
onChange={handleChange}   
/>
<Button 
onClick={handleClick} 
className="btn btn-success" 
type="submit" />
</form>

这是我的服务器端邮政编码

.post(async (req, res, next) => {
if (req.body.username.length !== 0) {
const newUser = new User({
userid: randomstring.generate({
length: 9,
readable : true,
charset: "alphanumeric",
}),
username: req.body.username
})
await User.find({username: newUser.username}, (err, result) => {
if (result.length) {
res.status(409).json({
message: "Username already exists! Try a different username"
})
}else {
User.create(newUser, (err, user) => {
if (!err) {
res.status(201).json({"user" : user})
}else {
res.status(400).json({"error" : error.message})
}
})
}
})
}else {
next(new Error("Body can't be empty"))
}
})

你的handleClick函数对我来说看起来不对,它应该是:

async function handleClick(event) {
event.preventDefault()
const body = { username }
let response;
let response_json;
try {
response = await fetch('http://localhost:5000/api/users', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body)
})
response_json = await response.json()
} catch (error) {
console.log(error.message)
}
}

希望这有所帮助。

编辑:根据评论者的建议进行了调整。虽然我最初的答案实际上有效,但这种新方法也应该适用于 async/await

编辑2:我刚刚意识到您的后端链接是通过http而不是https的。我实际上不确定您是否得到了回复,但如果您没有,可能是因为您使用 fetch 发布,要么 CORS 在后端阻止您,要么通过 fetch 完成的飞行前检查(选项(没有得到答复。

最新更新