1

我正在向我的 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总是未定义的。

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

有任何想法吗?


编辑

我正在使用koa-route.


编辑 2

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

4

1 回答 1

1

尝试使用 koa-body 解析器:

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

我认为 koa-router 会解析典型的请求内容、url 参数、表单等。如果你想解析包含 JSON 对象的请求的主体,你需要应用一个中间件(正如 alex 提到的那样)。

另外请检查您是否放置了有效的 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);
      }
    });
  }
};
于 2014-10-22T01:07:28.770 回答