Reputation: 643
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
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
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