preface

  • I wrote a little demo withkoa-bodyReceive processing request information, this time directly usedfromForm receipt, also incidentally is the old story
  • The demo address

From the form

  • There’s not much to say about this, but a long time ago, maybe in elementary school, remember filling in things on the webfromSubmission information is now mostly usedajaxOr JQ$ajaxOr isaxiosA library or something, I guess
  • <from>Is a tag that is used to submit the user form, i.e<input>
  • There are severalattributeYou have to write that down
    1. action– Specify where to send form data when submitting the form (i.e., fill in the submission address)
    2. method– Specify HTTP methods used to send form-data (POST, GET)
    3. enctype– Specify how to encode form data before sending it
      • application/x-www-form-urlencoded– Organize data into urlencode format
        • Key =value&key=value…
        • It is applicable to ordinary character content submission, and the submitted data is pure character
      • multipart/form-data– Binary data format
        • Applies to data submitted as impure characters, such as pictures, videos, etc
      • text/plain– Plain text submission
  • <form>Within the<input>usenameDistinguish between
  • use<input type="submit">submit
<form method="POST" action="/post" enctype="multipart/form-data">
    <p>Name:<input type="text" name="name" /></p>
    <p>Password:<input type="password" name="password" /></p>
    <input type="file" name="file">
    <input type="submit" value="Submit" />
</form>
Copy the code

koa-body

  • koa-bodykoaA body parser middleware
  • He consultedmulterModule, and add some expansion function

features

  • Can handle
    • multipart/form-data
    • application/x-www-urlencoded
    • application/json
    • application/json-patch+json
    • application/vnd.api+json
    • application/csp-report
    • text/xml
  • Not necessarilykoaSupport, can also be used directlynode
  • Support file upload
  • Support for body, field, and file size limits

The installation

npm install koa-body
Copy the code

A simple example

const Koa = require('koa');
const koaBody = require('koa-body');

const app = new Koa();

app.use(koaBody());
app.use(ctx= > {
    console.log(ctx.request.body);
    ctx.body = `Request Body: The ${JSON.stringify(ctx.request.body)}`;
});

app.listen(8080);
Copy the code

withkoa-routerCollocation is used

  • withkoa-routerCollocation allows you to: what interface do you want to use the parser on, just under that route
const Koa = require('koa');
const app = new Koa();
const KoaRouter = require('koa-router');
const KoaBody = require('koa-body');
const router = new KoaRouter();

router.post('/post', koaBody(), ctx= > {
    console.log(ctx.request.body);
    ctx.body = JSON.stringify(ctx.request.body);
});

app.use(router.routes());

app.listen(8080);
Copy the code

This parameter is optional

  • patchNode{Boolean} – Patch the request body to Node’sctx.req– the defaultfalse
  • patchKoa{Boolean} – Patch the request body tokoactx.request– the defaulttrue
  • jsonLimit{String | Integer} – byte limit of JSON subject – the default1mb
  • formLimit{String | Integer} – form the main body of byte limit – the default56kb
  • textLimit{String | Integer} – byte – the default text body56kb
  • encoding{String} – Sets the encoding of the incoming form fields – defaultutf-8
  • multipart{Boolean} – Parses multi-part entities (e.gform-data) – the defaultfalse
  • urlencoded{Boolean} – Parse the body of the default encoding – defaultfalse
  • text{Boolean} – Default parsing text body, such as XML – defaulttrue
  • json{Boolean} – Parse JSON body – defaulttrue
  • jsonStrict{Boolean} – Toggles strict mode, if set to true- parses arrays or objects only – defaulttrue
  • includeUnparsed{Boolean} – Toggles the returnRawBody option, if set to true, for form encodedand JSON requestsctx.request.body= >Symbol– Default appends the unparsed original request bodyfalse
  • formidable{Object} – Options passed to a powerful multi-part parser
    • maxFields{Integer} – Limits the number of fields that the query string parser will decode – default1000
    • maxFieldsSize{Integer} – Limits the amount of memory (in bytes) that all fields (except files) can be allocated together. If this value is exceeded, it is emitted by defaulterrorThe event2mb (2 * 1024 * 1024)
    • uploadDir{String} – Sets the directory to be used for file uploads – defaultos.tmpDir()
    • keepExtensions{Boolean} – File to write touploadDirWill include the extension of the original file, by defaultfalse
    • hash{String} – If you want to evaluate the checksum for an incoming file, set it to'sha1''md5'– the defaultfalse
    • multiples{Boolean} – Upload multiple files or no upload by default – defaulttrue
    • onFileBegin{Function} – A callback to the start of a file upload, which he can perform directly to rename the file before saving it to disk.To view the document
  • onError{Function} – Custom error handle, so you can customize the response if an error is thrown -onError (error, context) – is thrown by default
  • parsedMethods{String[]} – Declares the HTTP method used to parse the body – default['POST', 'PUT', 'PATCH']

Parsing body retrieval

  • ctx.request.body– in addition tofilesOutside the body of the
  • ctx.request.files– Uploaded files