Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'raw-body' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
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,
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}.`);
}
}
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();
});
async function rawBodyReader (ctx, next) {
const body = await getRawBody(ctx.req)
if (body) { ctx.body = body }
await next()
}
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'
]
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();
});
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;
}
}
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 {
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);
};
}
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());
}