Home > Back-end >  Why the delete method giving me unexpected token < in JSON at position 0 error?
Why the delete method giving me unexpected token < in JSON at position 0 error?

Time:05-05

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 Object] 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);
        });

CodePudding user response:

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 Object] so it is an object and not the string or number you expect
  • Related