首页 > 解决方案 > 带有正文的 axios DELETE 请求

问题描述

我正在尝试向我的 Express 服务器发出 Axios DELETE 请求。我浏览了所有讨论,但每个解决方案都不起作用。文档并没有很好地解释删除部分。

反应动作创建者

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 允许请求中的正文。但是我找到了其他解决方案,可以让它工作,但是,我没有运气。任何帮助将不胜感激!谢谢。

标签: javascriptreactjsexpressreduxaxios

解决方案


根据您的代码,在您的删除路由处理程序中,您至少有两个解决此问题的方法:

router.delete('/api/delete/post/:pid', (req, res, next) => {
console.log(req.params.pid); //your route params passed in http delete method
console.log(req.body.data); //your current value for pid
//const post_id = req.body.pid; <-- undefined as you don't passed this value
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);
                })
})

还想指出更改您的错误处理程序以获得更直接的方式来返回错误。

if (q_err) {
   //handle the q_err to not expose sensible data
   return req.status(500).json(q_err.message); //return some  meaningful error msg
}
res.status(200).json(q_res.rows);
//res.status(204).end() //no body response
//also when doing a delete you should not send a body.

用正文删除的证据

* Preparing request to http://localhost:3002/users/5ecddf90a544a74ef349c663
* Using libcurl/7.67.0 OpenSSL/1.1.1d zlib/1.2.11 nghttp2/1.29.0
* Current time is 2020-05-27T03:34:39.726Z
* Disable timeout
* Enable automatic URL encoding
* Enable SSL validation
* Enable cookie sending with jar of 4 cookies
* Hostname in DNS cache was stale, zapped
*   Trying 127.0.0.1:3002...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3002 (#6)

> DELETE /users/5ecddf90a544a74ef349c663 HTTP/1.1
> Host: localhost:3002
> User-Agent: insomnia/7.1.1
> Content-Type: application/json
> Accept: */*
> Content-Length: 104

|     {
|       "name": "eu1sad2",
|       "login": "adminsadad",
|       "password": "1lkajdhasdadsa0987"
|     }

* upload completely sent off: 104 out of 104 bytes
* Mark bundle as not supporting multiuse

< HTTP/1.1 204 No Content
< Access-Control-Allow-Origin: *
< Date: Wed, 27 May 2020 03:34:39 GMT
< Connection: keep-alive


* Connection #6 to host localhost left intact

没有正文的删除,仅用于比较:

* Preparing request to http://localhost:3002/users/5ecddff4a544a74ef349c664
* Using libcurl/7.67.0 OpenSSL/1.1.1d zlib/1.2.11 nghttp2/1.29.0
* Current time is 2020-05-27T03:35:47.358Z
* Disable timeout
* Enable automatic URL encoding
* Enable SSL validation
* Enable cookie sending with jar of 4 cookies
* Connection 7 seems to be dead!
* Closing connection 7
*   Trying 127.0.0.1:3002...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3002 (#8)

> DELETE /users/5ecddff4a544a74ef349c664 HTTP/1.1
> Host: localhost:3002
> User-Agent: insomnia/7.1.1
> Content-Type: application/json
> Accept: */*
> Content-Length: 0

* Mark bundle as not supporting multiuse

< HTTP/1.1 204 No Content
< Access-Control-Allow-Origin: *
< Date: Wed, 27 May 2020 03:35:47 GMT
< Connection: keep-alive


* Connection #8 to host localhost left intact

推荐阅读