2015-07-19 56 views
1

我试图处理我的koa路由器中的POST请求。不幸的是,每次我尝试使用我的表单发送数据时,我什么也得不到。我试过koa-bodyparser,没有运气。我使用Jade作为模板引擎。Koa路由器和POST

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

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是空的,this.request回报:方法,URL和报头。任何帮助感谢!

+1

尝试onerror选项https://github.com/koajs/bodyparser#options – monkey

+0

试过了 - 没有错误。谢谢:) – jwitos

+0

没有解决问题。尽管设法通过使用Socket.io来保存表单而不是使用POST发送来解决它。如果有人很好奇[这是github上的diff](https://github.com/jwitos/takismieszny/commit/a53e44b80ce474bcc30cda97cb8222ffeb666b51)我是怎么做到的。 – jwitos

回答

2

如果任何人在他们的搜索绊倒在此,我建议KOA体可以传递给POST请求,像这样:

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

但如果后期数据被发送到/游戏会发生什么/你说的问题?让我们转而蜷缩其无限的智慧。

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 

和日志的控制台上:

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

和当然,如果你的玉石是不正确没有任何机构解析器可以救你。