Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading