cojs / co-body

Parse request bodies with co
MIT License
325 stars 42 forks source link

I used this in koa with coffee script, but it always reported 'unexpected end of input' error #18

Closed hwoarangzk closed 9 years ago

hwoarangzk commented 9 years ago

index.coffee:

koa = require 'koa'
readFile = require './middlewares/readFile'
bodyParser = require './middlewares/bodyParser'

app = koa()

#app.use readFile
app.use bodyParser

app.listen 8080

and bodyParser.coffee:

parser = require 'co-body'

module.exports = (next) ->
    body = yield parser.json(this)
    console.log body
    yield next

Everytime when I refresh my page, it always reported:

  SyntaxError: Unexpected end of input
    at Object.parse (native)
    at C:\projects\node_modules\co-body\lib\json.js:35:25
    at IncomingMessage.onEnd (C:\projects\node_modules\co-body\node_modules\raw-
body\index.js:119:7)
    at IncomingMessage.g (events.js:199:16)
    at IncomingMessage.emit (events.js:104:17)
    at _stream_readable.js:907:16
    at process._tickCallback (node.js:372:11)

Is there anything I've done wrong? Thanks

fengmk2 commented 9 years ago
module.exports = (next) ->
    cosnole.log(this)
    body = yield parser.json(this)

I think there's a icon request.

fengmk2 commented 9 years ago

Maybe you should use https://github.com/koajs/bodyparser

haoxins commented 9 years ago

is the data valid json data?

hwoarangzk commented 9 years ago

@coderhaoxin I think is should be the valid json data because I did nothing on the request, I just used the co-body middleware. @fengmk2 I'll try the bodyparser you mentioned. Maybe the error has sth to do with the favicon request. Is there anyway to avoid the favicon request?

haoxins commented 9 years ago

oh, just like @fengmk2 said, you need https://github.com/koajs/bodyparser

you should not parser.json(this) for all the requests.

the error is from

JSON.parse(empty buffer)
hwoarangzk commented 9 years ago

@coderhaoxin So you mean that co-body won't filter out the empty buffer request while koa-bodyparser will?

fengmk2 commented 9 years ago

@hwoarangzk If you use parser.json directly, you need to check content-type first.

hwoarangzk commented 9 years ago

Thank you all :) I know how to modify my code.