hav*_*ish 1 javascript http node.js koa
我是nodejs的初学者.我正在尝试创建一个使用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;
}});
Run Code Online (Sandbox Code Playgroud)
如'/ 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
Run Code Online (Sandbox Code Playgroud)
以下是客户端代码:我使用了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`);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码是javascript - ES7,并且有效,因为我正在使用像Babel这样的转发器.重点是我能够成功地向服务器发送POST请求,但请求中没有正文.请提出一些解决方案.
使用的版本:节点v0.12.0,Koa v0.19.1
Koa默认不解析请求体,你需要为身体解析添加一个中间件,例如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"');
Run Code Online (Sandbox Code Playgroud)
Koa的理念是在核心框架中尽可能少地让人们通过组装专门的中间件来复合他们的系统.从我所看到的,有一些不同的包用于解析请求的主体,一些更简单,另一些有更多的功能/选项(例如koa-better-body).这一切都是为了给开发者提供选择而不创造一个巨大的巨石.
虽然这种方法起初可能看起来很奇怪,但我个人喜欢它:它允许我只选择我需要的功能而不会使框架膨胀,并为每个可能的用例提供选项.