簡體   English   中英

在KOA中未定義POST請求的請求正文

[英]Request body is undefined for POST request in 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不會解析請求主體,您需要添加一個用於主體解析的中間件,例如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 )。 所有這些都是在不創建大型組件的情況下為開發人員提供選擇。

雖然這種方法乍看起來似乎很奇怪,但我個人很喜歡:它允許我只選擇所需的功能,而不會為每個可能的用例添加過多的選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM