【发布时间】:2021-06-28 18:45:23
【问题描述】:
我不知道为什么这行之后的代码没有运行:
const res = await axios.post('http://localhost:4000/api/v1/comment', {
content,
});
评论在后端创建并保存到数据库中。服务器端代码有效,我在 Postman 中对其进行了测试,得到了正确的响应。我在前端的捕获中没有收到错误。请帮忙。
客户
CreateComment.js
try {
const res = await axios.post('http://localhost:4000/api/v1/comment', {
content,
});
//after this line does not run
//comment is successfully saved to database
console.log(res.body);
props.history.push(`/comment/${res.body.id}`);
} catch (err) {
console.error(err);
}
};
服务器
comment.js(控制器)
const create = async (req, res) => {
try {
const newComment = await Comment.create({
content: req.body.content,
});
return res.send(newComment);
} catch (e) {
console.error(e);
return res.status(400).send(e);
}
}
编辑:
Postman 中的响应正文:
{"id":34,"content":"happy tuesday","tone":"joy","updatedAt":"2021-04-01T16:06:07.333Z","createdAt":"2021-04-01T16:06:07.333Z"}
CreateComment.js(完整组件)
import React, { useState } from 'react';
import { withRouter } from 'react-router-dom';
import axios from 'axios';
function CreateComment(props) {
const [content, setContent] = useState('');
const handleSubmit = async () => {
try {
const res = await axios.post('http://localhost:4000/api/v1/comment',
{
content,
});
debugger;
console.log(res);
return props.history.push(`/comment/${res.data.id}`);
} catch (err) {
console.error(err);
}
};
return (
<div className='form'>
<form onSubmit={() => handleSubmit()}>
<div className='form-input'>
{/* Controlled Input */}
<input
type='text'
name='content'
onChange={e => setContent(e.target.value)}
value={content}
className='inputForm'
/>
</div>
<input type='submit' value='Curate' className='button' />
</form>
</div>
);
}
export default withRouter(CreateComment);
【问题讨论】:
-
你能显示
res的console.log输出吗?还是 Postman 输出或屏幕截图? -
在你的服务器文件中尝试返回
return res.status(201).send(newComment); -
@BikkiMahato 我添加了邮递员响应正文。
console.log(res.body)没有运行,history.push()我也没有改为:return res.status(201).send(newComment);但我仍然遇到同样的问题。 -
你可以尝试在你的axios调用中添加适当的标题,有时是与标题相关的问题。
-
当我运行前端代码时,评论被创建并保存到数据库中。
标签: javascript reactjs async-await promise axios