koajs / bodyparser Goto Github PK
View Code? Open in Web Editor NEWKoa body parsing middleware
License: MIT License
Koa body parsing middleware
License: MIT License
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
{}
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?
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!
ctx.request.body ever got empty object {}
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());
It's time to make bodyparser 3.2.x latest (not next)
ctx.request.body
the value will always return string type? right?
if i use the parameter https://github.com/node-modules/parameter
how to check number type?
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!
var fd = new FormData();
is this compatible with node 6?
"engines": {
"node": ">=7.6"
}
https://github.com/koajs/bodyparser/blob/master/package.json#L42
I'm using here https://github.com/entria/graphql-dataloader-boilerplate
this code run with node 6 using babel, do you think we can lower the node engine requirement?
Can we change it so we can access on ctx.req.body
as well? https://github.com/koajs/bodyparser/blob/3.x/index.js#L59
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.
Or is there a good reason not to? It gets a bit tedious having to write: if (this.request.body && this.request.body.foo)
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' }
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)
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 ?
What happend if a multipart form with file uploaded?
Whenever I have my browser fetch('...', {method: 'POST', body: <FormData>}), koa-bodyparser fails to parse it.
* <FormData> is an instance of FormData
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
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.
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"
{}
https://github.com/koajs/bodyparser/blob/next/index.js
It doesn't support ['text']
I parsed the body and it works, but if i dump the rawBody i get nothing.
the order was:
To be consistent with the other koajs repos, the branch for Koa 2.0 (currently named 3.0.0
) should be renamed to next
.
Hi,
I am switching from express to koa. I saw bodyparser for koa doesn't have verify function. Please consider this feature.
Thanks
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"
]
}
not sure req.charset
will be deprecated.
如何支持text/xml的POST请求呢?
I'm trying to migrate from KOA v1 to v2-alpha.
Looking for a bodyparser that's for v2. Please suggest some middlewares.
Thanks.
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.
Is there any easy way to get to the raw request body. Or is adding such a feature a possibility?
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
})
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;
//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 {}
@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?
Hi
It seems the current co-body version 1.0.0 have some issues on parsing array. Could you please update co-body to 1.1.x?
Thanks.
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
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);
Hey guys!
I see that async
is widely used in here but wouldn't it be better to have a promise implementation until async
is part of a node stable release?
https://github.com/koajs/bodyparser/blob/master/index.js#L69-L96
What are your thoughts on this?
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
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...)
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' ]
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
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?
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.
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
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
const bodyParser = require('koa-bodyparser');
app
.use(bodyParser())
error thrown:
"app.use() requires a generator function"
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.