Premise: Our company uses to upload files to KOA middleware first, then get the key value returned by Node middleware and upload it to Java background. Current requirements: Do not upload files to KOA, and the middle layer only forwards them to Java background

One: Here’s the problem

Previous koA2 uses koA-BodyParser for post requests and Koa-multer for image uploads, but koa-Multer and Koa-Route (note not the Koa-router) are incompatible. Besides, koA-bodyParser can’t get the requested body parameter, and the files uploaded by the Client can’t get the requested body parameter (no such field).

But both can be replaced with a KOA-body, and just a KOA-body.

The koa-body consists mainly of the following two dependencies:

Co - body ":" ^ 5.1.1 formidable ":" ^ 1.1.1"Copy the code

The implementation can be found on Github: github.com/dlau/koa-bo…

Two, the basic use of KOA-body

In using koa-body in KOA2, I used global import, not route level import, because there is no need to import only at the route level, considering that there are post requests or file upload requests in many places

1. Install dependencies

yarn add koa-body
## npm i koa-body -S
Copy the code

2, mian. Ts

Some other koA code has been omitted

import * as bodyParser from 'koa-body'; Const app = new Koa(); // Create Koa instance const app = new Koa(); app.use(cors({ origin: function () { return "*"; // Allow requests from all domain names}, exposeHeaders: [' www-authenticate ', 'server-authorization '], maxAge: 5, credentials: true, allowMethods: ['GET', 'POST', 'DELETE'], allowHeaders: ['Content-Type', 'Authorization', 'Accept'], })) app.use(bodyParser({ formLimit: '100MB ', jsonLimit:' 100MB ', textLimit:' 100MB ', multipart: true, // Can upload multiple files. This configuration is easy to ignore formidable: {maxFileSize:2000 * 1024 * 1024 // upload file size}})Copy the code

3. Useful parameters

1) Basic parameters of KOA-body

The title describe type The default value
patchNode Type the request body into ctx.req in native Node.js Boolean false
patchKoa Type the request body into KOA’s CTx. request Boolean true
jsonLimit Size limits for JSON data bodies String / Integer 1mb
formLimit Limit the size of the form request body String / Integer 56kb
textLimit Limit the size of the Text body String / Integer 56kb
encoding The default encoding of the form String utf-8
multipart Whether multipart-formdate forms are supported Boolean false
urlencoded Whether urlencoded forms are supported Boolean true
, etc.

2) Configuration parameters of formidable

The title describe type The default value
multipart Whether to upload multiple files Boolean true
, etc.

4. Obtain information about uploaded files

Note that if you want to obtain information about uploaded files, you need to obtain it in ctx.request.files.

If you want to get other form fields, you need to get them in ctx.request.body, which is determined by koA-body (the default).

This is the code that was uploaded to KOA and forwarded to Java

export const formdataOn = async function (config: PostConfig,ctx:any): Promise<object> { const form = new FormData(); // Undefined const file= ctx.request.files? .file as any; Const reader = fs.createreadStream (file? .path); for (const key in ctx.request.body) { if (Object.hasOwnProperty.call(ctx.request.body, key)) { const element = ctx.request.body[key]; form.append(key,element); } } form.append('file',reader) ; const res = await axios({ method: "post", url: config.url, data: form, headers: { ... form.getHeaders(), 'os-type': ctx.header['os-type'] } }); Let data = {count: res.data, respCode: res.respCode, respMsg: res.respMsg, headers:res.headers } return data; }Copy the code
Const res = await formdataOn(postConfig, CTX); ctx.body = JSON.stringify(res);Copy the code

This can then be forwarded to Java from the new FormData() front end to the Node side

But you wonder why you need new FormData() to upload files,

And “the content-type” : “multipart/form – data; charset=UTF-8”,

To find out, click on my next post to upload files for FormData() and Content-Type exploration

Reference:

Official Github for KoA-Body

Above content, inevitably there will be mistakes or cognitive bias, if there is a problem, I hope you leave a message to correct