本文介绍了在Koa中,接收POST请求时上下文对象为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Koa的新用户,正在创建一个演示应用程序.我想创建一个API来处理POST请求,但是当我console.log(ctx);时,在indexRouter.js中的ctx中没有任何内容,控制台仅打印诸如{}的空对象.

I am new in Koa and I am creating a demo app. I want to create an API to handle POST request, But when I console.log(ctx); then there is nothing in ctx in indexRouter.js, the console only printing empty object like {}.

我不知道为什么会这样.请有人建议我做错了什么吗?并且请帮助我通过POST方法获取request.body.

I don't know why this is happening. Please anyone suggest me where I am doing wrong?And please help me to get the request.body by POST Method.

serverKoa.js:

var koa = require('koa');
var router = require('koa-router');
var app = new koa();
var route = router(); //Instantiate the router

app.use(route.routes()); //Use the routes defined using the router
const index = require('./router/indexRouter')(route);

app.listen(3005 ,function(){
console.log("\n\nKoa server is running on port: 3005");
});

indexRouter.js:

var indexController=require('../controller/indexController');
module.exports = function (route) {
    route.post('/postnew',async ( ctx, next) => {
    console.log(ctx); // here  printing {}
  });
}

,我的请求对象(邮递员提供)是:

Method: POST,
url:http://localhost:3005/postnew
body:{
    "firstName":"viki",
    "lastName":"Kumar",
    "userName":"vk12kq14",
    "password":"098765432"
}
content-type:application/json

推荐答案

您的代码似乎有两个问题:

It looks like your code has two issues:

  • 您没有使用koa-router的下一个"版本,如果要使用async/await,则必须使用该版本.您可以这样安装它:

  • you're not using the "next" version of koa-router, which is required if you want to use async/await. You can install it like this:

npm i koa-router@next --save

  • 您没有使用koa-bodyparser来解析请求数据:

  • you're not using koa-bodyparser to parse the request data:

    npm i koa-bodyparser --save
    

  • 要使用:

    var koa        = require('koa');
    var router     = require('koa-router');
    var bodyParser = require('koa-bodyparser');
    
    var app        = new koa();
    app.use(bodyParser());
    ...
    

    已解析的正文数据将在您的路由处理程序中以ctx.request.body的形式提供.

    The parsed body data will be available in your route handlers as ctx.request.body.

    这篇关于在Koa中,接收POST请求时上下文对象为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-28 04:57