Reputation: 9963
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 {}
.
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 {}
});
}
and my request object ( by postman ) is:
Method: POST,
url:http://localhost:3005/postnew
body:{
"firstName":"viki",
"lastName":"Kumar",
"userName":"vk12kq14",
"password":"098765432"
}
content-type:application/json
Upvotes: 0
Views: 1914
Reputation: 203419
It looks like your code has two issues:
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
you're not using koa-bodyparser
to parse the request data:
npm i koa-bodyparser --save
To use:
var koa = require('koa');
var router = require('koa-router');
var bodyParser = require('koa-bodyparser');
var app = new koa();
app.use(bodyParser());
...
The parsed body data will be available in your route handlers as ctx.request.body
.
Upvotes: 2