【问题标题】:axios DELETE request with a body带有正文的 axios DELETE 请求
【发布时间】: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 允许请求中的正文。但是我找到了其他解决方案,可以让它工作,但是,我没有运气。任何帮助将不胜感激!谢谢。

【问题讨论】:

  • 您在两个单独的对象中有 dataheaders。带有headers 的那个作为第三个参数传递,这意味着它被忽略,这意味着Content-Type 没有正确设置,这意味着无法在服务器上解析正文。将dataheaders 放在同一个对象中,作为第二个参数传递。

标签: javascript reactjs express redux axios


【解决方案1】:

由于是删除请求,req.body 将显示未定义。相反,您将不得不使用req.params

router.delete('/api/delete/post/:pid', (res, req, next) => {
    console.log(req.params); //<----Here
    const post_id = req.params.pid; //<-----Here
    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);
                })
})

【讨论】:

【解决方案2】:

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

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

【讨论】:

  • 您好,感谢您的回复!我没有从中得到 console.log 打印语句......我不太清楚为什么。你写的我已经试过了。
  • 在你的实现中你必须重命名(req, res, next)的参数,目前你有(res, req, next)
  • 哇......我怎么没看到......你是个奇迹创造者!谢谢一堆。如果您不介意我问的话,我还有一个问题.. 为什么不使用 req.body.pid 工作?我以为我是从 React Action Creator 传递过来的
  • 是的,如果您将删除的第二个参数从:` { data: postId }` 更改为:` { pid: postId }` ,它可以这样工作。
  • 我以前有过,但没有用。所以我读了无数帖子说删除请求没有正文,所以你必须指定一个数据对象或其他东西。不太确定:S
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 2018-04-27
  • 2021-11-17
  • 1970-01-01
  • 2020-02-14
  • 2021-01-03
  • 2018-12-06
相关资源
最近更新 更多