Search code examples
jsonexpressweb-servicesfetch

request body is empty in backend while using fetch on express


I have a nodejs application where I have two scripts, server.js and script.js. The relevent code in both blocks are as follows:

script.js

    const topic = document.getElementById("topic").value;

    console.log("script:", topic);
    const response = await fetch("/generateLessonPlan", {
        method: "POST",
        headers: {
            "Content-Type": "application/json;",
        },
        body: JSON.stringify(topic),
    });

    const data = await response.json();

server.js

async function callAPI(request, response) {
    let topic = request.body;

    try {
        . . .
        console.log("server:", topic);
        . . .
    } catch (err) {
        . . .
    }
}

I have tried working with the codes on Postman where I send

{
        method: "POST",
        headers: {
            "Content-Type": "application/json;",
        },
        body: JSON.stringify(topic),
    }

as JSON and I am able to see it on my console but if I send it via the script.js through fetch, I notice that response.body is empty. I even ran 'console.log(request)' just to be sure and I noticed body: {}

Where am I going wrong such that I can't see the JSON if I run from script.js?


Solution

  • Since it doesn't work well from the scripts.js

    This seems to be wrong

      headers: {
            "Content-Type": "application/json;",
        },
    

    Remove the semi-colon ";" at the end of application/json

    • Make sure your server is configured to parse json add this

      app.use(express.json());

    Also, confirm that you need a valid input form element with an id of "topic" to be able to do this

     const topic = document.getElementById("topic").value;