Search code examples
javascriptnode.jskoakoa-router

How to create post request with Koa nodejs


I have just started with the Koa and made a basic setup with the following code

const Koa = require('koa');
const app = new Koa();

// logger

var port     = process.env.PORT || 8080; // set our port

// response

app.use(async ctx => {
  console.log(ctx.query)
  ctx.body = 'Hello World';
});

app.listen(port);
console.log('Magic happens on port ' + port);

Now when I hit the request http://localhost:8080 I get the request inside the console of ctx.query.

Question: How can I make a post and the get request with the koa framework?

Edit: I have now implemented Koa-router

const Koa = require('koa');
const koaBody = require('koa-body');
const router = require('koa-router')();
const app = new Koa();
app.use(koaBody());
// logger

router.get('/users', koaBody(),
  (ctx) => {
    console.log(ctx.request.query);
    // => POST body
    ctx.body = JSON.stringify(ctx.request.body);
  }
)

router.post('/user', koaBody(),
  (ctx) => {
    console.log('dfssssssssssssssssssssss');
    console.log(ctx);
    // => POST body
    // ctx.body = JSON.stringify(ctx.request.body);
  }
)

var port     = process.env.PORT || 8080; // set our port
app.use(router.routes());
app.listen(port);
console.log('Magic happens on port ' + port);

Still the problem is same. I can make a get request but not the post one.


Solution

  • use koa-router

    var Koa = require('koa');
    var Router = require('koa-router');
    
    var app = new Koa();
    var router = new Router();
    
    router.get('/', (ctx, next) => {
      // your get route handling
    });
    
    router.post('/', (ctx, next) => {
      // your post route handling
    });
    
    app
      .use(router.routes())
      .use(router.allowedMethods());