RockStar
RockStar

Reputation: 1314

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

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

Upvotes: 6

Views: 3888

Answers (2)

shriek
shriek

Reputation: 5833

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);
  }
});

Upvotes: 1

HelloWorld101
HelloWorld101

Reputation: 4386

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.

Upvotes: 5

Related Questions