如何使用Koa Node.js创建发布请求

时间:2018-12-24 06:42:56

标签: javascript node.js koa koa-router

我刚开始使用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请求。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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