Javascript 如何使用 Koa 解析多部分/表单数据体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33751203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse multipart/form-data body with Koa?
提问by eightyfive
Because I spent some (too much) time figuring out this simple requirement. I am documenting here the way to achieve multipart/form-data
body parsing with Koa.
因为我花了一些(太多)时间来弄清楚这个简单的要求。我在这里记录了multipart/form-data
使用 Koa实现body 解析的方法。
In my case, the reason of the confusion was the number of alternatives available out there:
就我而言,混淆的原因是可用的替代品数量:
And I wanted to find the most minimalist/close to express/koa/node
way/philosophy of doing things.
我想找到最简约/最接近express/koa/node
的做事方式/哲学。
So here it is. Below. In accepted answer. Hope this helps.
所以在这里。以下。在接受的答案中。希望这可以帮助。
采纳答案by eightyfive
You have to use koa-multeras stated in the official Koa wiki.
您必须按照官方Koa wiki中的说明使用koa-multer。
So a simple setup would look like:
所以一个简单的设置看起来像:
const koa = require('koa');
const multer = require('koa-multer');
const app = koa();
app.use(multer());
app.use(function *() {
this.body = this.req.body;
});
A couple of notes:
一些注意事项:
- Multer will only parse bodies of requests of type
multipart/form-data
- Noticethe use of
this.req.body
instead of Koa's superchargedthis.request
(not sure if this is intentional but this is confusing for sure... I would expect the parsedbody
to be available onthis.request
...)
- Multer 只会解析类型请求的主体
multipart/form-data
- 请注意使用
this.req.body
而不是 Koa 的增压this.request
(不确定这是否是故意的,但这肯定令人困惑......我希望解析的内容body
可以在this.request
......上使用)
And sending this HTML form as FormData
:
并将此 HTML 表单发送为FormData
:
<form>
<input type="hidden" name="topsecret" value="1">
<input type="text" name="area51[lat]" value="37.235065">
<input type="text" name="area51[lng]" value="-115.811117">
...
</form>
Would give you access to nested properties as expected:
会让您按预期访问嵌套属性:
// -> console.log(this.req.body)
{
"topsecret": 1,
"area51": {
"lat": "37.235065",
"lng": "-115.811117",
}
}
回答by silkAdmin
For Koa2, you can use async-busboyas other solutions dont support promisesor async/await.
对于Koa2,您可以使用async- busboy,因为其他解决方案不支持promises或async/await。
Example from the docs:
文档中的示例:
import asyncBusboy from 'async-busboy';
// Koa 2 middleware
async function(ctx, next) {
const {files, fields} = await asyncBusboy(ctx.req);
// Make some validation on the fields before upload to S3
if ( checkFiles(fields) ) {
files.map(uploadFilesToS3)
} else {
return 'error';
}
}
回答by satanas
I went through the same investigation than you and here are other ways to achieve multipart/form-data
body parsing with Koa.
我和你经历了同样的调查,这里有其他方法可以multipart/form-data
用 Koa实现身体解析。
co-busboy:
搭档:
var koa = require('koa');
var parse = require('co-busboy');
const app = koa();
app.use(function* (next) {
// the body isn't multipart, so busboy can't parse it
if (!this.request.is('multipart/*')) return yield next;
var parts = parse(this),
part,
fields = {};
while (part = yield parts) {
if (part.length) {
// arrays are busboy fields
console.log('key: ' + part[0]);
console.log('value: ' + part[1]);
fields[part[0]] = part[1];
} else {
// it's a stream, you can do something like:
// part.pipe(fs.createWriteStream('some file.txt'));
}
}
this.body = JSON.stringify(fields, null, 2);
})
koa-body:
koa-body:
var koa = require('koa');
var router = require('koa-router');
var koaBody = require('koa-body')({ multipart: true });
const app = koa();
app.use(router(app));
app.post('/', koaBody, function *(next) {
console.log(this.request.body.fields);
this.body = JSON.stringify(this.request.body, null, 2);
});
In both cases you will have a response like:
在这两种情况下,您都会得到如下响应:
{
"topsecret": 1,
"area51": {
"lat": "37.235065",
"lng": "-115.811117",
}
}
But personally, I prefer the way koa-body works. Plus, is compatible with other middleware like koa-validate.
但就个人而言,我更喜欢 koa-body 的工作方式。另外,与其他中间件兼容,如koa-validate。
Also, if you specify an upload dir to koa-body, it will save the uploaded file for you:
另外,如果你指定一个上传目录到 koa-body,它会为你保存上传的文件:
var koaBody = require('koa-body')({
multipart: true,
formidable: { uploadDir: path.join(__dirname, 'tmp') }
});
回答by ns16
I have three solutions that works for me:
我有三个适合我的解决方案:
- koa-body, note it parses
multipart/form-data
only withmultipart: true
option.
- koa-body,请注意它
multipart/form-data
仅解析multipart: true
选项。
const Koa = require('koa');
const koaBody = require('koa-body');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(koaBody({ multipart: true }));
router.post('/', async ctx => {
const body = ctx.request.body;
// some code...
});
app.use(router.routes());
app.listen(3000);
- koa-bodyparser, parses
multipart/form-data
only withkoa2-formidable
middleware before it.
- koa-bodyparser,
multipart/form-data
只解析koa2-formidable
它之前的中间件。
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const formidable = require('koa2-formidable');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(formidable());
app.use(bodyParser());
router.post('/', async ctx => {
const body = ctx.request.body;
// some code...
});
app.use(router.routes());
app.listen(3000);
- @koa/multer, note it parses
multipart/form-data
only if installedmulter
package. Also note thatkoa-multer
is deprecated, do not use it.
- @koa/multer,请注意它
multipart/form-data
仅在安装multer
包时解析。另请注意,koa-multer
已弃用,请勿使用它。
const Koa = require('koa');
const Router = require('koa-router');
const multer = require('@koa/multer');
const app = new Koa();
const router = new Router();
const upload = multer(); // you can pass options here
app.use(upload.any());
router.post('/', async ctx => {
const body = ctx.request.body;
// some code...
});
app.use(router.routes());
app.listen(3000);