javascript - KOA 中的 POST 请求未定义请求正文

标签 javascript node.js http 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;
    }});

正如案例“/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 请求,但请求中没有正文。请提出一些解决方案。

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

最佳答案

Koa默认不解析request body,需要添加中间件进行body解析,如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 的哲学是在核心框架中尽可能少,让人们通过组装专门的中间件来组合他们的系统。据我所知,有几个不同的包用于解析请求的主体,一些更简单,而另一些则具有更多功能/选项(例如 koa-better-body )。 这一切都是为了在不创建大型整体的情况下为开发人员提供选择。

虽然这种方法一开始可能看起来很奇怪,但我个人喜欢它:它允许我只选择我需要的功能,而不会为每个可能的用例提供选项而使框架膨胀。

关于javascript - KOA 中的 POST 请求未定义请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867642/

相关文章:

java - Java 中的 JSON 数组

javascript - 根据页面标题更改图像

javascript - 变量和数字的运算

javascript - Parse.com Node.js 通过 id 更新用户

sockets - 如何在 node.js 中分离 TCP 套接字消息

internet-explorer - 使用后退按钮: IE and Safari not reading from cache whereas Firefox and Chrome do

javascript - 为什么这个 javascript 对象引用前一个对象的属性?

javascript - 使用 promises 时如何在 Javascript 中出现异常后重试?

node.js - 使用 node.js 登录 Firebase-Admin

java - 带有代码 3xx 和空 'Location' header 的 HTTP 响应