How to access "request payload" in Koa web-framework?

3.5k Views Asked by At

We are using navigator.sendBeacon function to send data to Koa server, in which we are using bodyparser.

If we not wrapped data into form then by default this function send data as request payload. How I can able to access this data on Koa server?

Example -

navigator.sendBeacon('http://localhost:3000/cookies/', 'test=payload')

At server, request body is blank.

enter image description here

2

There are 2 best solutions below

0
HelloWorld101 On

Considering that

  1. Koa does not parse request body, so you need to use either koa-bodyparser or koa-body,

  2. koa-bodyparser by default has only json and form parsing enabled,

  3. From your screenshot, it is clear that navigator.sendBeacon set the Content-Type to text,

You need to change the Koa server code, so that it parses text data.

Example:

const Koa = require('koa'),
  bodyParser = require('koa-bodyparser'),
  app = (module.exports = new Koa());

app.use(bodyParser({ enableTypes: ['json', 'text'] }));

app.use(async (ctx) => {
  // ctx.request.body should contain the parsed data.
  console.log('Received data:', ctx.request.body);
  ctx.body = ctx.request.body;
});

if (!module.parent) app.listen(3000);

Tested with

koa 2.7.0,

koa-bodyparser 4.2.1.

0
shriek On

Although koa doesn't parse request body and for some reason you don't want to use koa-bodyparser you can still use the raw http to collect the body from request object.

app.use(async (ctx) => {  
  try {
    // notice that I'm wrapping event emitter in a `promise`
    ctx.body = await new Promise((resolve, reject) => {
        let data = '';
        // this is same as your raw `http.request.on('data', () => ()`
        ctx.req.on('data', chunk => {
          data += chunk;
        };
        ctx.req.on('error', err => {
          reject(err);
        };
        ctx.req.on('end', () => {
          resolve(data);
        };
      });
  } catch (e) {
    console.error(e);
  }
});