简体   繁体   English

在KOA中未定义POST请求的请求正文

[英]Request body is undefined for POST request in KOA

i am a beginner in nodejs. 我是nodejs的初学者。 I am trying to create an HTTP server that uses koa framework for handling HTTP requests. 我正在尝试创建一个使用koa框架处理HTTP请求的HTTP服务器。 Following is the code for my server. 以下是我的服务器的代码。

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

As mentioned in the case '/fudge/contact' the ctx.request.body is undefined. 如在'/ fudge / contact'案例中提到的,ctx.request.body是未定义的。 But, when I check for ctx.request or ctx.req, it shows content-length as 98(or something non-zero). 但是,当我检查ctx.request或ctx.req时,它显示的内容长度为98(或非零值)。

Following is the output that i get: 以下是我得到的输出:

============================

{ 
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

Following is the client code: I have used HttpClient library of aurelia framework. 以下是客户端代码:我使用了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`);

    }

The above code is javascript - ES7 and is valid as I am using transpilers like Babel. 上面的代码是javascript-ES7,在我使用Babel这样的编译器时有效。 Point is that i am able to send POST request to server successfully, but there is no body in the request. 关键是我能够将POST请求成功发送到服务器,但是请求中没有任何正文。 Please suggest some solution. 请提出一些解决方案。

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

Koa doesn't parse the request body by default, you need to add a middleware for body parsing, like koa-body for example: 默认情况下,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"');

Koa's philosophy is to have as little as possible in the core framework, and let people compound their system by assembling specialized middlewares. Koa的理念是尽可能减少核心框架,并让人们通过组装专门的中间件来组合其系统。 From what I have seen, there are a few different packages for parsing the request's body, some are simpler and others have more features/options (eg koa-better-body ). 从我所看到的内容来看,有几种不同的程序包可用于解析请求的正文,其中一些更简单,而另一些具有更多功能/选项(例如koa-better-body )。 It's all about giving choices to the developer without creating a big monolith. 所有这些都是在不创建大型组件的情况下为开发人员提供选择。

While this approach may seem strange at first, I personally like it: it allows me to choose only the features I need without bloating the framework with options for every possible use case. 虽然这种方法乍看起来似乎很奇怪,但我个人很喜欢:它允许我只选择所需的功能,而不会为每个可能的用例添加过多的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM