在express上使用fetch时,后端请求正文为空

问题描述 投票:0回答:1

我有一个 NodeJS 应用程序,其中有两个脚本:server.js 和 script.js。两个块中的相关代码如下:

脚本.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();

服务器.js

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

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

我尝试使用我发送的邮递员上的代码

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

作为 JSON,我可以在控制台上看到它,但是如果我通过 fetch 通过 script.js 发送它,我注意到 response.body 是空的。我什至运行“console.log(请求)”只是为了确定,我注意到

body: {}

如果我从 script.js 运行,我哪里出错了,看不到 JSON?

json express web-services fetch
1个回答
0
投票

因为它在scripts.js中不能很好地工作

这似乎是错误的

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

去掉分号“;”在 application/json 的末尾

  • 确保您的服务器已配置为解析 json 添加这个

    app.use(express.json());

另外,确认您需要一个 id 为“topic”的有效输入表单元素 能够做到这一点

 const topic = document.getElementById("topic").value;
© www.soinside.com 2019 - 2024. All rights reserved.