I am trying to make an Axios DELETE request to my Express server. I've looked through every discussion and each solution does not work. Documentation didn't really explain the delete part very well.
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');
}
Basically the Express server sees the request, but the body or data is not present.
Express server to handle request
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);
})
})
From the Express server code, when I do console.log(req.body)
, I get "Cannot read property of '...' of undefined". From my research, it appears only GET, PUT, PATCH allows for the body in the request. But I've found other solutions that allowed for this to work, however, I have no luck in this. Any help would be greatly appreciated! Thanks.