J
J
JordanBelford2021-02-13 06:20:44
Node.js
JordanBelford, 2021-02-13 06:20:44

Why does undefined come up when sending a PUT request?

Good afternoon! I send a fetch request from the client with this body: body: JSON.stringify({"id": "2"}). I process this put request from the server side, but undefined comes to the request body, what is the problem?

Серверная часть:
router.put('/', async (req, res) => {
    const {id} = req.body;
    res.send(console.log(id))
});
Клиентская часть:
fetch('http://localhost:5000/api', {
            method: 'PUT',
            body: JSON.stringify({
                "id": "2"
            })
        })

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex K, 2021-02-13
@JordanBelford

The problem seems to be that the middleware is asynchronous, and there is no notification about the end of its execution (it is not called next()).
Option 1. Either remove asyncit - judging by the synchronous operation of the content, it is not needed here:

router.put('/', (req, res) => {
    const {id} = req.body;
    console.log(id);
    res.send(id);
});

Option 2. If you still plan some asynchronous work inside the middleware, then use next() to announce the end of the execution of the asynchronous middleware
router.put('/', async (req, res, next) => {
    const {id} = req.body;
    console.log(id);
    res.send(id);
    next();
});

UPD1: In the client side, when accessing /api, the "content-type" header corresponding to the passed body is not passed.
It should be like this:
fetch('http://localhost:5000/api', {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                "id": "2"
            })
        })

UPD2: as Igor Makhov rightly noted - you hardly need console.log in res.send.

I
Igor Makhov, 2021-02-13
@Igorgro

Are you kidding? Why do you res.sendneed console.log?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question