Hello fellow stackoverflow members,
The Problem
as described in the titel I have a problem parsing an string to JSON.
The string I want to parse is send by the client to the server with a POST Method. The request is handled by this function on the server:
async function handleReservierung (req: Http.IncomingMessage, res: Http.ServerResponse): Promise<void> {
res.setHeader("Content-Type", "application/json");
res.setHeader("Access-Control-Allow-Headers", "content-type");
res.setHeader("Access-Control-Allow-Origin", "*");
let body: string = "";
req.on("data", chunk => {
body += chunk.toString();
});
req.on("end", () => {
console.log(JSON.parse(body));
res.end(body);
});
}
I've read about incoming POST requests and how to handle them and saw this solution with the incoming chunks added up in the variable body. So far so good.
I thought probably the chunks were not added correctly but as I console.log(body)
it would give me a perfectly valid string:
{"ids":["600c4eff6c54c802cc1cac4f","600c4f576c54c802cc1cac51"],"name":"Someons Name"}
like so tested in a JSON validator.
I built an Interface
interface Reservierungen {
ids: number[];
name?: string;
}
which is the one used on the client Side to fill out all the data and then its getting send in the Body of the request with JSON.stringify(body)
When it now ty to JSON.parse(body)
on the server it throws this error:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (C:UsersfelixDocumentsGISGIS-WiSe2020_2021serverindex.js:72:26)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Why do I need to Parse the JSON?
I want to get the data from the JSON Object to update my MongoDB. I thought I could just parse the JSON string send in the body and use it to update the DB. After being stuck for quite a while I am kindly asking for you advice now :)
Important to know
Due to the limitations of our uni project: not useing any library like express or jquery I am asking for nativ typescript solutions.
I assume something is wrong with the string but I can't figure out what it is. I already tried to trim of the whitespaces which did not help either.
I hope I gave you all the information needed.
Thank you in advance.
question from:
https://stackoverflow.com/questions/65921678/json-parse-throws-syntaxerror-unexpected-end-of-json-input