Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

node.js - Json.parse throws: "SyntaxError: Unexpected end of JSON input"

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I figured it out.

The problem was that I did copy the fetch from MDN and enabled CORS on the fetch() statement .
With CORS enabled there comes a preflight Request (CORS Details) which has an OPTIONS header. My Typescript server wasent configured to accept CORS requests (so no way to handle OPTIONS header) and did try to use the udefined body of the preflight Request.

I disabled the CORS header on the fetch() statement. Which resulted in a working JSON.parse()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...