'Why the delete method giving me unexpected token < in JSON at position 0 error?

I am getting errors while trying to delete data, I tried it on postman, it works fine, but browser is giving me this errors:

DELETE http://localhost:5000/items/[object%20Object] 404 (Not Found)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Client-side:

<button onClick={() => handleDeleteItem(_id)}>DELETE BUTTON</button>
const handleDeleteItem = id => {
        const deletion = window.confirm('Do you really want to delete the item?');
        if(deletion){
            const url = `http://localhost:5000/items/${id}`;
            fetch(url, {
                method: 'DELETE',
                headers: {
                    'content-type': 'application/json'
                },
            })
            .then(res=>res.json())
            .then(data =>{
                console.log(data);
            })
        }
    }

Server-side:

app.post('/items/:id', async(req, res) =>{
            const id = req.params.id;
            const query = {_id: ObjectId(id)};
            const result = await itemsCollection.deleteOne(query);
            res.send(result);
        });


Solution 1:[1]

You have 'content-type': 'application/json' but haven't put JSON in the body so the JSON parsing middleware is trying to parse the empty body and throwing an exception.

Don't lie about what content you are sending.


Asides:

  • app.post looks for a POST request but you are making a DELETE request
  • id is being converted to [object%20Object] so it is an object and not the string or number you expect

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin