![](/img/trans.png)
[英]Body-parser doesn't work with typescript, when I send a request, I'm getting an undefined in request.body
[英]I can't access my request.body object in Koa JS (I am using body parser middleware but still it's not working)
我的主 server.js 文件
const koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const app = new koa();
var router = new Router();
// app.use(bodyParser({ enableTypes: ["json", "text"] }));
// I have also tried passing enabletypes parameteres but it still is not working..
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());
router.post("/", async (ctx) => {
console.log(ctx);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server started on port no ${PORT}`));
当我点击这个 router.post("/") 端点时......只是为了查看我的上下文对象,我控制台记录了上下文对象,当我使用邮递员点击这个端点时,它在控制台中显示以下内容(我是在请求中发送 JSON 正文)
我的邮递员请求
如何访问我的正文(JSON 对象)?
要访问您的 body 对象,请尝试以下操作:
const body = ctx.request.body;
其次:因为在其中一条评论中有一条注释,为什么你会得到 404。我想这是因为在你的路线中你没有返回任何东西。 所以你的路线可能看起来像:
router.post("/", async (ctx) => {
const body = ctx.request.body;
console.log(body);
return (true) // or whatever you want to return to the client
});
我建议使用一些东西来返回,即如果你什么都不返回,你将得到一个带有 Koa 的 404。 只需设置 ctx 的主体,即ctx.body="something here"
。
除此之外,这取决于您在应用程序中使用什么来击中它 Postman 的工作方式可能略有不同并传递额外的标头等。我在 VS Code 上使用 Thunder Client 时遇到过几次这种情况,它在戳它时工作但在该应用程序的东西有点不对劲。 我只在 Koa 上遇到过这个问题,从来没有表达过,所以可能值得在应用程序中检查和记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.