GithubHelp home page GithubHelp logo

bodyparser's Introduction

NPM version build status Coveralls node version

Koa body parsing middleware, based on co-body. support json, form and text type body.

Parse incoming request bodies in a middleware before your handlers, available under the ctx.request.body property.

⚠ Notice: This module doesn't support parsing multipart format data, please use @koa/multer to parse multipart format data.

Install

NPM

$ npm i @koa/bodyparser --save

Usage

const Koa = require("koa");
const { bodyParser } = require("@koa/bodyparser");

const app = new Koa();
app.use(bodyParser());

app.use((ctx) => {
  // the parsed body will store in ctx.request.body
  // if nothing was parsed, body will be an empty object {}
  ctx.body = ctx.request.body;
});

Options

  • patchNode: patch request body to Node's ctx.req, default is false.

  • enableTypes: parser will only parse when request type hits enableTypes, support json/form/text/xml, default is ['json', 'form'].

  • encoding: requested encoding. Default is utf-8 by co-body.

  • formLimit: limit of the urlencoded body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 56kb.

  • jsonLimit: limit of the json body. Default is 1mb.

  • textLimit: limit of the text body. Default is 1mb.

  • xmlLimit: limit of the xml body. Default is 1mb.

  • jsonStrict: when set to true, JSON parser will only accept arrays and objects. Default is true. See strict mode in co-body. In strict mode, ctx.request.body will always be an object(or array), this avoid lots of type judging. But text body will always return string type.

  • detectJSON: custom json request detect function. Default is null.

    app.use(
      bodyParser({
        detectJSON(ctx) {
          return /\.json$/i.test(ctx.path);
        },
      })
    );
  • extendTypes: support extend types:

    app.use(
      bodyParser({
        extendTypes: {
          // will parse application/x-javascript type body as a JSON string
          json: ["application/x-javascript"],
        },
      })
    );
  • onError: support custom error handle, if koa-bodyparser throw an error, you can customize the response like:

    app.use(
      bodyParser({
        onError(err, ctx) {
          ctx.throw(422, "body parse error");
        },
      })
    );
  • enableRawChecking: support the already parsed body on the raw request by override and prioritize the parsed value over the sended payload. (default is false)

  • parsedMethods: declares the HTTP methods where bodies will be parsed, default ['POST', 'PUT', 'PATCH'].

  • disableBodyParser: you can dynamic disable body parser by set ctx.disableBodyParser = true.

    app.use((ctx, next) => {
      if (ctx.path === "/disable") ctx.disableBodyParser = true;
      return next();
    });
    app.use(bodyParser());

Raw Body

You can access raw request body by ctx.request.rawBody after koa-bodyparser when:

  1. koa-bodyparser parsed the request body.
  2. ctx.request.rawBody is not present before koa-bodyparser.

Koa v1.x.x Support

To use koa-bodyparser with [email protected], please use bodyparser 2.x.

$ npm install koa-bodyparser@2 --save

usage

const Koa = require("koa");
const bodyParser = require("@koa/bodyparser");

const app = new Koa();
app.use(bodyParser());

app.use((ctx) => {
  // the parsed body will store in ctx.request.body
  // if nothing was parsed, body will be an empty object {}
  ctx.body = ctx.request.body;
});

Licences

MIT

bodyparser's People

Contributors

3imed-jaberi avatar adipascu avatar atian25 avatar caryyu avatar coderzzp avatar dead-horse avatar esco avatar fengmk2 avatar greenkeeperio-bot avatar haoxins avatar i5ting avatar jameshfisher avatar joelcolucci avatar markherhold avatar popomore avatar rudijs avatar satazor avatar scragg0x avatar sgywzy avatar sylvainlap avatar thaiworldgame avatar titanism avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bodyparser's Issues

4.1 Unexpected token function

bodyparser(4.1) in Koa(2.2.0)

just use like app.use(bodyParser());

error showed as below:

/some/path/node_modules/koa-bodyparser/index.js:69
  return async function bodyParser(ctx, next) {
               ^^^^^^^^
SyntaxError: Unexpected token function
    at Object.exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:513:28)
    at Module._extensions..js (module.js:550:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/zhangyan/Documents/Zalaxy/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/some/path/server/app.js:4:20)

koa-bodyparser type check failed

koa-bodyparser failed to parse body. Request info below:

curl 'http://localhost:3000/service/user' -H 'Content-Type: json' -H 'Accept: */*' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --data-binary 'name=cp' --compressed

Package versions: [email protected], [email protected].

After debug I found the reason is:

function* parseBody(ctx) {
    // ctx.request.is(jsonTypes) check fails
    // And current content-type is: `'content-type': 'json'`
    if ((detectJSON && detectJSON(ctx)) || ctx.request.is(jsonTypes)) {
      ctx.request.body = yield parse.json(ctx, jsonOpts);
    } 

Is it a bug, or just a compatibility issue?

koa2 async/await does not works

I'm using babel to compile async/await style code in my koa2 projects.
Unfortunately, koa-bodyparser@next does not parse request body as expected:
context.request.body always eqls to {} .

I'm just have a little test using jQuery:
$.post(some_url, {<k,v>}, result => {...some handle...})

Here is my koa config:
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

other code:
router.post('/ajax/ban/join', banJoinController);

//banJoinController.js

export default async(ctx) => {
  console.log(ctx.query)//works well -> koa-router
  console.log(ctx.request.body)// == {}
  //do sth. async
  ctx.body = {code: 0, message: 'test'};
}

Maybe I missed sth. important, help me pls!

An error on onerror

When you pass --header "Content-Encoding: fake", the onerror function doesn't get called. Looks like some inner library is just returning < HTTP/1.1 415 Unsupported Media Type by itself.

this.req._readableState.ended is true

I'm not quite sure how to replicate yet, this has been happening every so often on my project. I'm using emberjs and a normal run of the mill POST to my server which is running koa.

Nothing out of the ordinary it would seem http://cl.ly/image/1Z2a332O2U3v

But in koa, this.request.body is undefined.

I did some digging and the reason the body is not getting parsed is because 1) this.request doesn't have my JSON for some reason and 2) this.req._readableState.ended is true.

Again, the ajax call is very standard

let ajaxOptions = {
    url,
    data,
    method,
    xhrFields: {
        withCredentials: true
    }
};
// if POST or PUT
ajaxOptions.contentType = 'application/json';
ajaxOptions.data = JSON.stringify(ajaxOptions.data);

Any idea what could cause the JSON body to not show up in koa? It's obviously being sent by the browser as seen in that chrome screenshot. http://cl.ly/image/1Z2a332O2U3v

Unexpected token `function`

I wanted to use this middleware in the ES7 based Javascript app, I get following error

esharapov/koa-es7-test/node_modules/koa-bodyparser/index.js:72
  return async function bodyParser(ctx, next) {
               ^^^^^^^^
SyntaxError: Unexpected token function
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Module._extensions..js (module.js:579:10)
    at Object.require.extensions.(anonymous function) [as .js] (/home/esharapov/koa-es7-test/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)

is it an issue with my setup, babel or bodyparser ?

Parse JSON using the wrong method

This module can parse point

Example:

request

'{"a1": "xx", "a2": "cc.init"}'

ctx.request.body

{ '{"a1": "xx", "a2": "cc': { 'init"}': '' } }

but useing JSON.parse

{ a1: 'xx', a2: 'cc.init' }

Koa Body Parser Unexpected Token

Trying to run koa-bodyparser here I get this error:

/home/lucas/Works/backend/node_modules/koa-bodyparser/index.js:72
  return async function bodyParser(ctx, next) {
               ^^^^^^^^
SyntaxError: Unexpected token function
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Module._extensions..js (module.js:579:10)
    at Object.require.extensions.(anonymous function) [as .js] (/home/lucas/Works/backend/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)

My code is:

/**
 * Created by Lucas Teske on 11/04/17.
 * @flow
 */

import 'isomorphic-fetch';

import Koa from 'koa';
import cors from 'koa-cors';
import graphqlHTTP from 'koa-graphql';
import convert from 'koa-convert';
import logger from 'koa-logger';
import koaSsl from 'koa-ssl';
import route from 'koa-route';
import bodyParser from 'koa-bodyparser';


const app = new Koa();
app.use(koaSsl({ disabled: !sslEnforce }));
app.use(logger());
app.use(bodyParser());

Reading raw data doesn't appear to work

Surely I'm doing something wrong, but this isn't working for me:

'use strict';
const koa = require('koa');
const bodyParser = require('koa-bodyparser');

const app = koa();
app.use(bodyParser({
  enableTypes: ['text']
}));
app.use(function *() {
  this.body = this.request.body;
});
app.listen(3000);
$ curl -v --data 'Hello world' localhost:3000
* Rebuilt URL to: localhost:3000/
* Hostname was NOT found in DNS cache
*   Trying ::1...
* Connected to localhost (::1) port 3000 (#0)
> POST / HTTP/1.1
> User-Agent: curl/7.37.1
> Host: localhost:3000
> Accept: */*
> Content-Length: 11
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 11 out of 11 bytes
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Content-Length: 2
< Date: Thu, 19 May 2016 03:29:36 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
{}

Usage with Windows10

Hello all,

I am trying to using bodyparser with next flag. Everything seems fine until I send a POST request. The body seems to be empty all the time. I investigated the issue and came up with incompatible dependency with Windows10.
koa-bodyparser

Is there a workaround to by-pass this problem?

Thanks!
Uğurcan

`extendTypes` error

If we extends the type by options, we will get errors reported by type-is module, when I look into the source code, I find the issue is the extendType function:

function extendType(original, extend) {
  if (extend) {
    if (!Array.isArray(extend)) extend = [extend];
    extend.forEach(original.push.bind(original));
  }
}

After push a extended types {json:["app/x", "app/y"]}, the original will become

[
// default
0,
"app/x",
["app/x", "app/y"],
1,
"app/y",
["app/x", "app/y"]
]

If the check for app/x succeeds, it will be ok. But if fails or check for app/y, it will throw an error.

In addition, the test passes because just only test the 'app/x'. If we modify the test for extent type should extent json ok to

      request(app.listen())
        .post('/')
        .type('application/y-javascript')
        .send(JSON.stringify({ foo: 'bar' }))
        .expect({ foo: 'bar' }, done);

The test will fail.

Implement with plain Promises instead of async-await

I love async-await, but this module now requires me to update to node 7.6 which still isn't very supported by some modules like bcrypt.

I know this isn't koa-bodyparser's problem, but Koa 2 itself can run on Node 6 with plain promises while installing (official Koa) middleware requires 7.6 which feels like a disconnect.

Using plain promises shouldn't be too hard in this case and would also inevitably give better performance (micro but it's free) and wider support.

Raw data?

Is there any easy way to get to the raw request body. Or is adding such a feature a possibility?

Is `null` a valid body?

I'm starting to think my fix in issue #14 was a bit off. Originally the idea was make it so this.body.foo was always safe and would never throw, however I've run into a case that breaks that. Someone can send the json body null, which we put in this.body which makes this.body.foo throw.

The two fixes I can think, is we never allow null as a body, and convert it to {} or maybe revert #14 and document that this.body.foo is not "safe" unless you check the existence of this.body first

Usage example for 3.x doesn't work?

Hi,

The usage example for 3.x doesn't seem to work?

var bodyParser = require('koa-bodyparser');
var koa = require('koa');

var app = new koa();
app.use(bodyParser());

app.use(function(ctx, next) {
  // the parsed body will store in this.request.body
  // if nothing was parsed, body will be an empty object {}
  ctx.body = ctx.request.body;
});

app.listen(3000);

Once the app server is running if I send a POST request with some data I just get an empty object returned?

$ curl http://127.0.0.1:3000 -F foo="bar"
{}

how to detect invalid JSON and response some helpful message?

some guy may try to post some wired string and set header to be json, i can caught the error but don't know how to response a custom message that tell them," dude, your json is invalid !"

i tried something like this:

app.use(function*(next){
    if(/get|delete|head/i.test(this.method)) return yield next;
    if( /json/i.test( this.get('Content-Type') ) ){
      try{
        require('co-body').json(this)()....... blah blah blah.....
      }catch(e){

      }
    }

    yield bodyParser({
      formLimit: '200kb',
      jsonLimit: '1mb',
    }).call(this,next)
  });

i looked the source code, there is no error handling;

Bodyparser causing 404 error if `await` is not used with `next` in any previous middleware

For this simple koa2 server:

app.use(async (ctx, next) => {
  next();
});

app.use(bodyParser({ enableTypes: ['json'] }));
app.use(async (ctx) => (ctx.status = 200));

Client calls:

fetch('/', {method: 'post', headers: {'Content-Type': 'application/json'}})

The return is status 404 - Not Found.

If I change the first middleware by adding await:

app.use(async (ctx, next) => {
  await next();
});

then it works as expected.

SyntaxError: Unexpected token

Problem:
I start up app.js with babel-node, but when I import 'body-parser', an error throw:
/koa-bodyparser/index.js:69
return async function bodyParser(ctx, next) {
SyntaxError: Unexpected token function
Package.json:
"dependencies": {
"koa": "^2.0.1",
"koa-bodyparser": "^4.1.0",
"koa-logs-full": "0.0.8",
"koa-router": "^5.4.0",
"koa-static-cache": "^4.0.0",
"superagent": "^3.5.0"
},
"devDependencies": {
"babel-cli": "^6.23.0",
"babel-loader": "^6.3.2",
"babel-plugin-transform-async-to-generator": "^6.22.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-stage-0": "^6.22.0"
}
.babelrc:
{
"presets": [
"stage-0", "es2015"
],
"plugins": [
"transform-async-to-generator"
]
}

post request can't get the value

//app.js
var  bodyParser = require('koa-bodyparser');
app.use(bodyParser());
//new.ejs
<!DOCTYPE html>
<html>
<head>
    <% include ./../common/header.ejs %>
</head>
<body>
<div class="panel panel-default">
    <div class="panel-heading"><h1><%= title %></h1></div>
    <div class="panel-body">
        <form class="form-horizontal" action="/users/create" method="post">
            <div class="form-group">
                <label for="email" class="col-sm-2 control-label">邮箱</label>
                <div class="col-sm-10">
                    <input type="email" class="form-control" id="email" placeholder="邮箱" value="<%= user.email %>">
                </div>
            </div>

            <div class="form-group">
                <label for="nickname" class="col-sm-2 control-label">用户名</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="nickname" placeholder="用户名" value="<%= user.nickName %>">
                </div>
            </div>

            <div class="form-group">
                <label for="password" class="col-sm-2 control-label">密码</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" id="password" placeholder="密码" value="<%= user.password %>">
                </div>
            </div>

            <div class="form-group">
                <label for="phone" class="col-sm-2 control-label">电话</label>
                <div class="col-sm-10">
                    <input type="number" class="form-control" id="phone" placeholder="电话" value="<%= user.phone %>">
                </div>
            </div>

            <div class="form-group">
                <label for="imgUrl" class="col-sm-2 control-label">头像</label>
                <div class="col-sm-10">
                    <input type="url" class="form-control" id="imgUrl" placeholder="头像链接" value="<%= user.imgUrl %>">
                </div>
            </div>

            <div class="form-group">
                <label for="address" class="col-sm-2 control-label">地址</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="address" placeholder="地址" value="<%= user.address %>">
                </div>
            </div>

            <div class="form-group">
                <label for="gender" class="col-sm-2 control-label">性别</label>
                <div class="col-sm-10">
                    <select name="gender" id="gender" title="">
                        <option value="0" selected>请选择</option>
                        <option value="1">男</option>
                        <option value="2">女</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-success">提交</button>
                    <a href="/users" class="btn btn-default">返回</a>
                </div>
            </div>
        </form>
    </div>
</div>

</body>
</html>

//user.model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//创建模型
var UserSchema = new Schema({
    email: String,
    nickName: String,
    password: String,
    salt: String,
    gender: Number,
    phone: Number,
    imgUrl: String,
    address: String,
    createTime: Date,
    lastLogin: Date
});

//注册并导出
module.exports = mongoose.model('User', UserSchema);
user.router.js
router.get('/new', add);
router.post('/create', save);
function *add(next) {
    yield this.render('/users/new', {
        title: '添加用户',
        user: {
            email: '',
            nickName: '',
            password: '',
            gender: 0,
            phone: 1,
            imgUrl: '',
            address: ''
        }
    });
}

function *save(next) {
    console.log(this.request.body);
    var user = this.request.body;
    user.createTime = new Date;
    user.lastLogin = new Date;
    var id = users.push(user)
    users.id = id - 1;
    this.redirect('/users');
}
module.exports = router;

console.log(this.request.body) is {}

KOA v2 support?

I'm trying to migrate from KOA v1 to v2-alpha.
Looking for a bodyparser that's for v2. Please suggest some middlewares.
Thanks.

Propagate error to error handler

Hello,

I have a Koa 2 app like this

  app
    .use(errorHandler)
    .use(bodyParser)

bodyParser:

bodyParser({
  formLimit: 0,
  onerror (err, ctx) {
    throw new BadRequest('Error parsing body.', err);
  },
});

errorHandler:

  try {
    await next();
  } catch (err) {
    // Do something with err
  }

when an error is thrown in onerror it doesn't get passed to the errorHandler like normal requests but instead throw:

error: UnprocessableEntityError: body parse error
    at Object.throw (/Users/matteo/dev/transactions-server/node_modules/koa/lib/context.js:91:23)
    at onerror (bodyParser.js:9:5)
    at /Users/matteo/dev/transactions-server/node_modules/koa-bodyparser/index.js:61:15
    at process._tickCallback (node.js:401:9)

there's no way of handling error like normal response handlers?

I can use ctx.throw but would really like to propagate the error

POST json body isn't set on `ctx.request.body`

When I POST to my endpoint with a JSON body its not showing up on the server:

{
	"queries": ["pizza", "javascript"]
}

I get undefined for ctx.request.body

sending as form data seems to be ok for non-json objects. but I want to post json.

I've tried posting with both application/javascript and application/json neither work. (i'm using "koa-bodyparser": "^3.2.0" with "koa": "^2.0.0",)

Here is relevant app.js:

app
  .use(bodyParser())
  .use(cors({
    methods: ['GET', 'PUT', 'POST', 'PATCH', 'DELETE']
  }));

middleware(app);
routes(app);

post array more than 21

I have two Nodejs Apps: App A and App B
App A post array data to App B

Like this:

let list = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20' ]
request({
     method: 'POST',
     url,
     form: {
          list: list,
     }
}, function...)

App B get the array perfect
screen shot 2016-10-21 at 6 10 48 pm

But if we change the "list" to a array, which length more than 21, something weird happened.

let list = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21' ]

screen shot 2016-10-21 at 6 09 57 pm
App B get a array something like map.

I googled the keywords, like "post array 21", "post array to object", can't find useful infomations.

I kind of confused, is there anyone who know the reason about this?

Environment
Nodejs: v6.6.0
Koa: 2.0.0
koa-bodyparser: 3.2.0
Request: 2.74.0

How to get the formdata?

How can I get the data in koa2?

//html
        function sendForm(){
            var fd = new FormData();
            fd.append("name",$('#name').val());
            console.log('开始post数据');
            fd.append('aaa','我们的故事');
            $.ajax({
                type:'POST',
                dataType:'JSON',
                processData: false,  // 告诉JSLite不要去处理发送的数据
                contentType: false,   // 告诉JSLite不要去设置Content-Type请求头
                data:fd,
                url:'/api/test/',
                success:function(data){
                    console.log('success:',data)
                },
                error:function(err){
                    console.log('error:',err)
                }
            })
        }

//koa2
router
  .post('/test/', (ctx) => {
console.log(ctx.request.body.name);//undefined
  })

Combine with co-body

@dead-horse I think that the line between this package and co-body is getting increasingly thinner. Some patches, like the one that adds support for json-patch, was initially targeted for co-body and then moved and merged here. The code surface covered by co-body is really small. Would you accept a PR that ports its features to here?

can't install

when i was run
npm install koa-bodyparser --save
it show that:
no such file or directory, stat 'file:node_shrinkwrap/co-4.6.0.tgz'
how i install koa-bodyparser
thx

Query strings are not parsed as arrays

If I do a GET request and pass an array, the browser sends it over as id[] id[] as expected. But koa parser doesn't see it as an array. It comes through as

qs { 'ids[]': 
   [ '55fb67079a5940a6ac32ab08',
     '5606eadad5689ece061d726b',
     '5606ebfa4c872978085c325f' ] }

Chrome screenshot
image

how to install @next version?

its not really clear how to install bodyparser for koa v2. Ive tried to do npm i koa-body-parser@next but it does not work

Parse body only on some routes

Is it possible to use koa-bodyparser in connection with koa-router and parse the request body only on some routes? If so, what is the best way to do it? Thanks!

fail to parse form data

Whenever I have my browser fetch('...', {method: 'POST', body: <FormData>}), koa-bodyparser fails to parse it.

* <FormData> is an instance of FormData

koa-bodyparser cannot recognize content-type with charset

When i am using koa-bodyparser, it works well with 'Content-Type': 'application/json', but when the request's 'Content-Type' is 'application/json;charset=utf-8', its body cannot be parsed and i get only a {}
Here below is a screenshot of both situation. thanks.

aaaa

raw-body doesn't seem to work

I parsed the body and it works, but if i dump the rawBody i get nothing.

the order was:

  1. middleware
  2. console log body <- works
  3. console log rawBody <- nothing

if nothing was parsed why does ctx.request.body have a value?

If nothing was parsed why does ctx.request.body have a value (empty object)?

In both these cases ctx.request.body equals {}:
a) The request body was empty
b) The request body was '{}'

How do I distinguish whether the request body was empty or '{}'? What's the recommended method to test whether the request body is empty?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.