How to use raw-body - 10 common examples

To help you get started, we’ve selected a few raw-body examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github slackapi / steno / src / record / http-proxy.ts View on Github external
href: null,
      method: requestInfo.method,
      path: requestInfo.url,
    });

    if (this.requestInfoHook !== undefined) {
      proxyReqOptions = this.requestInfoHook.processor(req, proxyReqOptions);
    }

    proxyReqOptions.headers = fixRequestHeaders(proxyReqOptions.hostname, proxyReqOptions.headers);

    log('creating proxy request with options: %O', proxyReqOptions);
    const proxyRequest = this.requestFn(proxyReqOptions);
      // TODO: are response trailers really set on `req`?
    req.pipe(proxyRequest);
    rawBody(req)
      .then((body) => {
        requestInfo.body = body;
        requestInfo.trailers = cloneJSON(req.trailers);
        this.emit('request', requestInfo);
      })
      .catch((error) => {
        log(`request body read error: ${error.message}`);
      });
    proxyRequest.on('response', (proxyResponse: IncomingMessage) => {
      log('recieved proxy response');
      const responseInfo: ResponseInfo = {
        body: undefined,
        headers: (cloneJSON(proxyResponse.headers) as NotOptionalIncomingHttpHeaders),
        httpVersion: proxyResponse.httpVersion,
        requestId: requestInfo.id,
        statusCode: proxyResponse.statusCode as number,
github graphql / express-graphql / src / parseBody.js View on Github external
throw httpError(415, `Unsupported charset "${charset.toUpperCase()}".`);
  }

  // Get content-encoding (e.g. gzip)
  const contentEncoding = req.headers['content-encoding'];
  const encoding =
    typeof contentEncoding === 'string'
      ? contentEncoding.toLowerCase()
      : 'identity';
  const length = encoding === 'identity' ? req.headers['content-length'] : null;
  const limit = 100 * 1024; // 100kb
  const stream = decompressed(req, encoding);

  // Read body from stream.
  try {
    return await getBody(stream, { encoding: charset, length, limit });
  } catch (err) {
    throw err.type === 'encoding.unsupported'
      ? httpError(415, `Unsupported charset "${charset.toUpperCase()}".`)
      : httpError(400, `Invalid body: ${err.message}.`);
  }
}
github bidanjun / koa-graphql-next / src / __test__ / http-post.spec.js View on Github external
app.use(async (ctx, next) => {
        if (ctx.is('*/*')) {
            const req = ctx.req;
            ctx.request.body = await rawBody(req, {
                length: req.headers['content-length'],
                limit: '1mb',
                encoding: null
            });
        }
        await next();
    });
github jembi / openhim-core-js / src / koaMiddleware.js View on Github external
async function rawBodyReader (ctx, next) {
  const body = await getRawBody(ctx.req)

  if (body) { ctx.body = body }
  await next()
}
github elementary / houston / src / houston / index.js View on Github external
app.use(async (ctx, next) => {
  ctx.request.rawBody = await rawBody(ctx.req, {
    length: ctx.req.headers['content-length'],
    limit: '1mb'
  })
  .then((buf) => buf.toString())
  .catch((err) => { throw new Error(500, err.message) })

  const jsonTypes = [
    'application/json',
    'application/json-patch+json',
    'application/vnd.api+json',
    'application/csp-report'
  ]

  const formTypes = [
    'application/x-www-form-urlencoded'
  ]
github entria / graphql-vigilant-bot / src / app.js View on Github external
app.use(async (ctx, next) => {
  if (!ctx.request.headers['content-length'] || !ctx.request.headers['content-type']) {
    return;
  }

  ctx.request.rawBody = await getRawBody(ctx.req, {
    length: ctx.request.headers['content-length'],
    limit: '5mb',
    encoding: contentType.parse(ctx.request).parameters.charset,
  });

  ctx.request.body = JSON.parse(ctx.request.rawBody);

  await next();
});
github windsome / koa3-wechat / samples / server.js View on Github external
async payNotify (ctx, next) {
        var rawText = await getRawBody(ctx.req, {
            encoding: 'utf-8'
        });
        //debug ("get notify: ", rawText);
        try {
            var retobj = await this.wepay.notifyParse (rawText);
            debug ("payNotify parsed:", retobj);
            emitter.wechatSendOut({cmd:'payNotify', payload: retobj});
            var xml = this.wepay.notifyResult({return_code: 'SUCCESS', return_msg: 'OK'});
            debug ("payNotify process ok: ", xml);
            ctx.body = xml;
        } catch (e) {
            debug ("payNotify error: ", e);
            var xml = this.wepay.notifyResult({return_code: 'FAILURE', return_msg: 'FAIL'});
            ctx.body = xml;
        }
    }
github zeit / next.js / packages / next / next-server / server / api-utils.ts View on Github external
export async function parseBody(req: NextApiRequest, limit: string | number) {
  const contentType = parse(req.headers['content-type'] || 'text/plain')
  const { type, parameters } = contentType
  const encoding = parameters.charset || 'utf-8'

  let buffer

  try {
    buffer = await getRawBody(req, { encoding, limit })
  } catch (e) {
    if (e.type === 'entity.too.large') {
      throw new ApiError(413, `Body exceeded ${limit} limit`)
    } else {
      throw new ApiError(400, 'Invalid body')
    }
  }

  const body = buffer.toString()

  if (type === 'application/json' || type === 'application/ld+json') {
    return parseJson(body)
  } else if (type === 'application/x-www-form-urlencoded') {
    const qs = require('querystring')
    return qs.decode(body)
  } else {
github phenyl / phenyl / modules / express / src / index.ts View on Github external
method !== "GET" &&
        method !== "POST" &&
        method !== "PUT" &&
        method !== "DELETE"
      ) {
        return next();
      }
      const serverLogic = new ServerLogic(serverParams);
      const encodedHttpRequest: EncodedHttpRequest = {
        method,
        headers: headers as EncodedHttpRequest["headers"],
        path,
        qsParams: query
      };
      if (!body) {
        encodedHttpRequest.body = await getRawBody(req, true);
      } else if (typeof body === "object") {
        encodedHttpRequest.parsedBody = body;
      } else {
        encodedHttpRequest.body = body;
      }

      const response = await serverLogic.handleRequest(encodedHttpRequest);
      res
        .status(response.statusCode)
        .header(response.headers)
        .send(response.body);
    };
  }
github jlipps / triager / lib / es6 / utils.js View on Github external
async function parsePayload (ctx) {
  ctx.request.body = await getRawBody(ctx.req, {
    length: ctx.req.headers['content-length'],
    limit: '1mb'
  });
  ctx.request.json = JSON.parse(ctx.request.body.toString());
}

raw-body

Get and validate the raw body of a readable stream.

MIT
Latest version published 3 months ago

Package Health Score

83 / 100
Full package analysis

Popular raw-body functions

Similar packages