ax ios запрос DELETE с телом - PullRequest
0 голосов
/ 27 мая 2020

Я пытаюсь отправить запрос Ax ios DELETE своему серверу Express. Я просмотрел все обсуждения, и каждое решение не работает. Документация не очень хорошо объясняет часть удаления.

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 допускают тело в запросе. Но я нашел другие решения, которые позволили этому сработать, однако мне в этом не повезло. Любая помощь будет принята с благодарностью! Спасибо.

Ответы [ 2 ]

0 голосов
/ 27 мая 2020

Согласно вашему коду, у вас есть как минимум два решения этой проблемы в обработчике маршрута удаления:

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
0 голосов
/ 27 мая 2020

Так как это запрос на удаление, req.body покажет undefined. Вместо этого вам нужно будет использовать 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);
                })
})
...