Koa路由器和POST [英] Koa-router and POST

查看:135
本文介绍了Koa路由器和POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的koa-router中处理POST请求.不幸的是,每次我尝试使用表单发送数据时,我什么也得不到.我试过了koa-bodyparser,那里没有运气.我正在使用Jade作为模板引擎.

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

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和标头.任何帮助表示赞赏!

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

推荐答案

万一有人在搜索中偶然发现此问题,让我建议将koa-body传递给这样的发布请求:

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

但是如果将帖子数据发送到您说的/game/questions会发生什么?让我们转向其无限的智慧.

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

在日志控制台上:

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

当然,如果您的玉器不正确,那么任何人体分析器都无法拯救您.

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

这篇关于Koa路由器和POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆