First of all, please don't criticize me. I am beginner and I started to learn the server and working on it. But almost all the time I regularly found this error. I search this question and want's to know properly about it. But now I am becoming more confused because I don't know the major reason of showing this error. So, Please help me. As a beginner, It is the only errors that frustrates me a lot.
In the command Line I found this error
SyntaxError: Unexpected token 1 in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (C:\Projects\book-stock-server\node_modules\body-parser\lib\types\json.js:160:10)
at parse (C:\Projects\book-stock-server\node_modules\body-parser\lib\types\json.js:83:15)
at C:\Projects\book-stock-server\node_modules\body-parser\lib\read.js:128:18
at AsyncResource.runInAsyncScope (node:async_hooks:199:9)
at invokeCallback (C:\Projects\book-stock-server\node_modules\raw-body\index.js:231:16)
at done (C:\Projects\book-stock-server\node_modules\raw-body\index.js:220:7)
at IncomingMessage.onEnd (C:\Projects\book-stock-server\node_modules\raw-body\index.js:280:7)
at IncomingMessage.emit (node:events:402:35)
at endReadableNT (node:internal/streams/readable:1343:12)
In the Client Side, I basically want's to decrease quantity 1 by 1 by clicking (handleDelivered) button and sent the quantity as a request to the server to store the quantity in MongoDB database. But when I implement this functionality it doesn't work and shows that error in the command line.
const handleDelivered = () => {
const updatedQuantity = { quantity: quantity - 1 };
const url = `http://localhost:5000/books/${id}`;
(async () => {
try {
const res = await fetch(url, {
method: "PUT",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(updatedQuantity.quantity)
})
const data = await res.json();
if (data.modifiedCount >= 1) {
setbookInfo({ ...bookInfo, quantity: updatedQuantity.quantity });
}
}
catch (err) {
console.error(err);
toast.error("There was a server side error");
}
})();
}
Here in the server side I did exactly to store the quantity in the database and send the response to the client
const id = req.params.id;
const updatedQuantity = req.body;
const filter = { _id: ObjectId(id) };
const option = { upsert: true };
const updatedDoc = {
$set: {
quantity: updatedQuantity.quantity
}
};
const result = await bookCollection.updateOne(filter, updatedDoc, option);
res.send(result);
})