简体   繁体   中英

Koa-router and POST

I'm trying to handle POST request within my koa-router. Unfortunately, every time I try to get data send using my form, I get nothing. I've tried koa-bodyparser, no luck there. I'm using Jade as template engine.

router.js:

var jade = require('jade');
var router = require('koa-router')();
var bodyParser = require('koa-bodyparser');
exports.enableRouting = function(app){
  app.use(bodyParser())      
  router.get('/game/questions', function *(next){
    this.status = 200;
    this.body = jade.renderFile('game_questions.jade');
  });
  router.post('/game/questions', function *(next){
    console.log(this.request.body);
    this.status = 200;
    this.body = jade.renderFile('game_questions.jade');
  });
  app
      .use(router.routes())
      .use(router.allowedMethods());
}

and part of game_questions.jade :

form(method='post' id='New_Question_Form')
  input(type='text', id='New_Question_Text')
  input(type='submit' value='Add Question')

this.request.body is empty, this.request returns: method, URL and header. Any help appreciated!

In case anyone stumbles upon this in their searches, let me suggest koa-body which may be passed to a post request like so:

var koa = require('koa');
var http = require('http');
var router = require('koa-router')();
var bodyParser = require('koa-body')();

router.post('/game/questions', bodyParser, function *(next){
  console.log('\n------ post:/game/questions ------');
  console.log(this.request.body);
  this.status = 200;
  this.body = 'some jade output for post requests';
  yield(next);
});

startServerOne();

function startServerOne() {
  var app = koa();
  app.use(router.routes());
  http.createServer(app.callback()).listen(8081);
  console.log('Server 1 Port 8081');
}

but what would happen if post data was sent to /game/questions you say? Let us turn to curl in its infinite wisdom.

curl --data "param1=value1&pa//localhost:8081/game/questions'
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 34
Date: Thu, 17 Dec 2015 21:24:58 GMT
Connection: keep-alive

some jade output for post requests

And on the console of logs:

------ post:/game/questions ------
{ param1: 'value1', param2: 'value2' } 

And of course, if your jade is incorrect no body parser can save you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM