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

2

6

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

Amieva answered 3/12, 2018 at 10:21 Comment(1)
see enableTypes option for koa-bodyparser.Donell
O
5

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.

Overwind answered 11/6, 2019 at 14:3 Comment(0)
J
1

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);
  }
});
Jacquesjacquet answered 9/5, 2021 at 22:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.