Next.js Discord

Discord Forum

JSON parsing error when running 'await request.json()'

Unanswered
Cuban Martin posted this in #help-forum
Open in Discord
Avatar
Cuban MartinOP
I have this snippet of code that sends a post request to an api endpoint

function order() {
        const date = Date();
        const data = {
            orderDate: date,
            cart: cart
        }
        try {
            fetch('http://localhost:3000/api/orders', {
                method: "POST",
                body: JSON.stringify(data),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then((res) => console.log(res));
        } catch (error) {
            console.log(error);
        }
        
    }


on the api endpoint, I'm trying to get the body of the request, but I keep getting this error "SyntaxError: Failed to parse JSON"

on the endpoint I'm simply console.logging the request body with "console.log(await request.json())".

Using nextjs 14.0.2

7 Replies

Avatar
Try doing res.ok to check if the response's status returned successfully.
Avatar
Cuban MartinOP
The api endpoint works. I can get a response. My issue is why the request.body() is giving me a json parsing error.
Avatar
Do what i said first.
Also i dont think using the url like that in a fetch is a good idea
The reason it can't parse is either because the response didnt return correctly OR the response you are sending is incorrect itself.
Avatar
Cuban MartinOP
I'm not having the issue in the code posted above. That's the client side request. I am having the issue on the api endpoint handler. The api receives the POST request from the code above, but when I try to get the information from the body using "const body = await request.json", it gives a syntaxerror cannot parse json.
The json in the post request looks find to me from the code above, so I'm not sure why it cannot parse the json in the request body