为什么PUT请求体未定义?
我正在向我的koajs服务器发出以下请求:
$.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
总是未定义的。
如果我将请求types更改为POST,它工作正常。
有任何想法吗?
编辑
我正在使用koa-route
。
编辑2
刚刚意识到我正在使用koa-body-parser
,这可能更相关。
尝试使用koa-body分析器:
const bodyParser = require('koa-bodyparser') app.use(bodyParser())
我认为koa路由器将parsing典型的请求的东西,URL参数,forms等。如果你想parsing包含JSON对象的请求的正文,你需要申请一个中间件(如亚历克斯暗指)。
另外请检查,看看你是否有效的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的限制。 然后共同体/ 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); } }); } };