Profer
Profer

Reputation: 643

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.

Upvotes: 1

Views: 11555

Answers (2)

Tian
Tian

Reputation: 86

use koa-router and the koa-bodyparser middleware

var Koa = require('koa');
var bodyParser = require('koa-bodyparser');
var Router = require('koa-router');

var app = new Koa();
var router = new Router();
app.use(bodyParser());

router
  .get('/', (ctx, next) => {
    ctx.body = 'Hello World!';
  })
  .post('/users', (ctx, next) => {
    // handle your post request here
    ctx.body = ctx.request.body;
  })
  .put('/users/:id', (ctx, next) => {
    // ...
  })
  .del('/users/:id', (ctx, next) => {
    // ...
  })
  .all('/users/:id', (ctx, next) => {
    // ...
  });
app
  .use(router.routes())
  .use(router.allowedMethods());

Upvotes: 6

Jay Lane
Jay Lane

Reputation: 1401

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());

Upvotes: 4

Related Questions