2014-10-21 53 views
1

我做了如下要求我koajs服务器:为什么PUT请求体未定义?

$.ajax({ 
    type  : 'PUT',  // this.request.body undefined server side 
    // type   : 'POST', // this.request.body all good server side 
    url   : url, 
    data  : body, 
    dataType : 'json' 
}) 

但在服务器端this.request.body永远是不确定的。

如果我将请求类型更改为POST,它工作正常。

任何想法?


编辑

我使用koa-route


EDIT 2

刚刚意识到我使用的是koa-body-parser,这可能是更相关。

+1

你用什么中间件来解析请求体? – 2014-10-22 00:08:45

+0

我使用'koa-route',这似乎是自动解析请求正文? – Felix 2014-10-22 00:36:09

回答

1

尝试使用KOA体解析器:

const bodyParser = require('koa-bodyparser') 
app.use(bodyParser()) 

我觉得如果要分析包含一个JSON的请求体KOA路由器将解析典型要求的东西,网址参数,表格等。对象你需要申请一个中间件(如亚历克斯暗示)。

此外请检查您是否正在使用有效的JSON。

看看这个KOA-bodyparser:

/** 
* @param [Object] opts 
* - {String} jsonLimit default '1mb' 
* - {String} formLimit default '56kb' 
* - {string} encoding default 'utf-8' 
*/ 

    return function *bodyParser(next) { 
    if (this.request.body !== undefined) { 
     return yield* next; 
    } 

    if (this.is('json')) { 
     this.request.body = yield parse.json(this, jsonOpts); 
    } else if (this.is('urlencoded')) { 
     this.request.body = yield parse.form(this, formOpts); 
    } else { 
     this.request.body = null; 
    } 

    yield* next; 
    }; 

有看起来是对JSON量的1MB限制。然后co-body/lib/json.js

module.exports = function(req, opts){ 
    req = req.req || req; 
    opts = opts || {}; 

    // defaults 
    var len = req.headers['content-length']; 
    if (len) opts.length = ~~len; 
    opts.encoding = opts.encoding || 'utf8'; 
    opts.limit = opts.limit || '1mb'; 

    return function(done){ 
    raw(req, opts, function(err, str){ 
     if (err) return done(err); 

     try { 
     done(null, JSON.parse(str)); 
     } catch (err) { 
     err.status = 400; 
     err.body = str; 
     done(err); 
     } 
    }); 
    } 
}; 
+0

为响应而欢呼!嗯,我刚刚意识到我已经在使用'koa-body-parser' ...任何想法为什么它解析POST的请求体而不是PUT? – Felix 2014-10-22 03:16:55

+0

嗯不 - 你可能需要挖掘源代码。 koa的东西很新。 – akaphenom 2014-10-22 16:16:18

+0

增加了一些细节 – akaphenom 2014-10-22 16:22:32