我有一个应用程序,我需要发送数据从React前端到Koa服务器。问题是我不知道如何在Koa中打印出请求正文。
在React中,我在单击时运行此代码
fetch("/metafield", {
method: "POST",
body: JSON.stringify({
key: "key",
value: "value",
value_type: "string",
namespace: "namespace",
}),
});只需在Koa服务器端点上使用body进行简单的抓取。
在Koa中,我有这样的功能
router.post("/metafield", (ctx) => {
console.log(ctx.request.body);
});由于某种原因,这将返回空的对象{}。
我还试着用
const bodyParser = require("koa-bodyparser");
const server = new Koa();
server.use(bodyParser());如建议的here,但输出仍然是相同的。在那之后,我尝试将bodyParser添加到koa-router中,如下所示
const router = new Router();
router.use(bodyParser());但我仍然在Koa应用程序中得到空对象。
提前感谢
发布于 2020-07-02 16:18:00
好吧。解决方案很简单。
当我添加了
headers: {
"Content-Type": "application/json",
},当使用fetch发送请求时
请求现在应该如下所示
fetch("/metafield", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
key: "key",
value: "value",
value_type: "string",
namespace: "namespace",
}),
});https://stackoverflow.com/questions/62691349
复制相似问题