【发布时间】:2020-05-27 02:26:20
【问题描述】:
我正在尝试向我的 Express 服务器发出 Axios DELETE 请求。我浏览了所有讨论,但每个解决方案都不起作用。文档并没有很好地解释删除部分。
React Action Creator
export const deleteDbPost = (postId) => async(dispatch) => {
console.log(postId);
const response = await axios.delete(`http://localhost:8000/api/delete/post/${postId}`,
{ data: postId },
{
headers: {
"Authorization": localStorage.getItem("access_token") !== null ? `Bearer ` + localStorage.getItem("access_token") : null,
"Content-Type": "application/json"
}
}
);
console.log(response);
dispatch({ type: DELETE_DB_POST, payload: response.data });
history.push('/posts');
}
基本上,Express 服务器会看到请求,但正文或数据不存在。
Express 服务器处理请求
router.delete('/api/delete/post/:pid', (res, req, next) => {
console.log(req.body);
const post_id = req.body.pid;
pool.query(`DELETE FROM posts
WHERE pid=$1`, [post_id], (q_err, q_res) => {
if (q_err) return next(q_err); // Note: Why do we use next here?? res.json(q_res.rows);
console.log(q_err);
res.json(q_res.rows);
})
})
从 Express 服务器代码中,当我执行 console.log(req.body) 时,我得到“无法读取未定义的 '...' 的属性”。根据我的研究,似乎只有 GET、PUT、PATCH 允许请求中的正文。但是我找到了其他解决方案,可以让它工作,但是,我没有运气。任何帮助将不胜感激!谢谢。
【问题讨论】:
-
您在两个单独的对象中有
data和headers。带有headers的那个作为第三个参数传递,这意味着它被忽略,这意味着Content-Type没有正确设置,这意味着无法在服务器上解析正文。将data和headers放在同一个对象中,作为第二个参数传递。
标签: javascript reactjs express redux axios