![](/img/trans.png)
[英]Axios post entering catch block even after successful Rest API call completion
[英]code after await axios post call is not running, no error in catch block
我無法弄清楚為什么這行之后的代碼沒有運行:
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);
}
};
服務器
評論.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.