1

我刚刚开始Koa并使用以下代码进行了基本设置

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

现在,当我点击请求时,http://localhost:8080我会在ctx.query.

问题:如何使用 koa 框架提出请求postget

编辑:我现在已经实现了 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);

问题还是一样的。我可以提出get要求,但不能提出要求post

4

2 回答 2

5

使用 koa-router 和 koa-bodyparser 中间件

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());
于 2018-12-24T07:24:16.960 回答
3

使用 koa 路由器

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());
于 2018-12-24T07:14:50.393 回答