KOA中的POST请求未定义请求主体

我是nodejs的初学者。 我正在尝试创build一个使用koa框架来处理HTTP请求的HTTP服务器。 以下是我的服务器的代码。

app.use(function * (next){ var ctx = this; var resource = url.parse(ctx.request.url, true, true).pathname; switch(resource) { case '/': resource = config.app.root + '/dist/index.html'; ctx.type = mime.lookup(resource); ctx.body = fs.readFileSync(resource, 'utf-8'); ctx.response.set('Access-Control-Allow-Origin', '*'); break; case '/fudge/contact': console.log('============================'); console.log(ctx.request); // no body console.log('============================'); console.log(ctx.req); // no body console.log('============================'); console.log(ctx.request.body) // is undefined break; default: resource = config.app.root + resource; ctx.type = mime.lookup(resource); ctx.body = fs.readFileSync(resource, 'utf-8'); ctx.response.set('Access-Control-Allow-Origin', '*'); break; }}); 

正如“/ fudge / contact”中提到的那样,ctx.request.body是未定义的。 但是,当我检查ctx.request或ctx.req时,它显示的内容长度为98(或非零)。

以下是我得到的输出:

 ============================ { method: 'POST', url: '/fudge/contact', header: { host: 'localhost:9090', 'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0', accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'accept-language': 'en-US,en;q=0.5', 'accept-encoding': 'gzip, deflate', 'content-type': 'text/plain; charset=UTF-8', referer: 'http://localhost:9090/', 'content-length': '98', connection: 'keep-alive', pragma: 'no-cache', 'cache-control': 'no-cache'}} ============================ { _readableState: { objectMode: false, highWaterMark: 16384, buffer: [], length: 0, ... more lines but no body. ============================ undefined 

以下是客户端代码:我已经使用了aurelia框架的HttpClient库。

  contactUs(){ this.http.createRequest('/fudge/contact') .asPost() .withBaseUri('http://localhost:9090') .withHeader('Content-Type','text/plain') .withContent('{"heading":this.heading, "firstName":this.firstName, "lastName":this.lastName, "query":this.query}') .send(); alert(`Thank you, ${this.fullName}, your query has been successfully submitted`); } 

上面的代码是JavaScript – ES7,因为我使用像Babel这样的转译器。 要点是我能够成功发送POST请求到服务器,但请求中没有主体。 请build议一些解决scheme。

使用的版本:节点v0.12.0,Koa v0.19.1

Koa默认不parsing请求体,你需要添加一个中间件来parsing正文,比如koa-body :

 var app = require('koa')(), router = require('koa-router'), koaBody = require('koa-body')(); app.use(router()); app.post('/users', koaBody, function *(next) { console.log(this.request.body); // => POST body this.body = JSON.stringify(this.request.body); } ); app.listen(3131) console.log('curl -i http://localhost:3131/ -d "name=test"'); 

Koa的理念是在核心框架中尽可能less,让人们通过组装专门的中间件来组合他们的系统。 从我所看到的,有几个不同的包来parsing请求的主体,有些更简单,有些则有更多的特性/选项(例如koa-better-body )。 这完全是为了给开发者提供select,而不是创build一个巨大的巨石。

虽然这种方法起初看起来很奇怪,但我个人喜欢它:它允许我只select我所需要的function,而不用为每个可能的用例select框架。