我无法弄清楚为什么此行之后的代码不运行:
const res = await axios.post('http://localhost:4000/api/v1/comment', {
content,
});
评论在后端创建并保存到数据库中。服务器端代码有效,我在 Postman 中测试了它,并得到了正确的响应。我在前端的捕获中没有收到错误。请帮忙。
客户
创建评论.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);
axios
请求是在此处表单的提交事件上发出的。提交时的默认行为是提交表单并导航到新的 URL,这会导致浏览器中止请求,因为它假定不再需要该请求。将 e.preventDefault();
添加到事件处理程序将解决此问题,这是一个工作示例:
https://codesandbox.io/s/react-router-playground-forked-s9op7?file=/index.js
我面临着几乎同样的问题,但是我添加了 e.preventDefault() ,但等待 axios.post 之后的 console.log(res) 没有被触发。