mirror of
https://github.com/p-stream/simple-proxy.git
synced 2026-01-11 20:10:35 +00:00
Fix forgotten awaits + prevent double reading
This commit is contained in:
parent
3e8d413a87
commit
c0ce4c9e84
3 changed files with 21 additions and 4 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import { getBodyBuffer } from '@/utils/body';
|
||||
import {
|
||||
getProxyHeaders,
|
||||
getAfterResponseHeaders,
|
||||
|
|
@ -11,7 +12,7 @@ export default defineEventHandler(async (event) => {
|
|||
// parse destination URL
|
||||
const destination = getQuery<{ destination?: string }>(event).destination;
|
||||
if (!destination)
|
||||
return sendJson({
|
||||
return await sendJson({
|
||||
event,
|
||||
status: 400,
|
||||
data: {
|
||||
|
|
@ -19,12 +20,16 @@ export default defineEventHandler(async (event) => {
|
|||
},
|
||||
});
|
||||
|
||||
// read body
|
||||
const body = await getBodyBuffer(event);
|
||||
|
||||
// proxy
|
||||
cleanupHeadersBeforeProxy(event);
|
||||
await proxyRequest(event, destination, {
|
||||
fetchOptions: {
|
||||
redirect: 'follow',
|
||||
headers: getProxyHeaders(event.headers),
|
||||
body,
|
||||
},
|
||||
onResponse(outputEvent, response) {
|
||||
const headers = getAfterResponseHeaders(response.headers, response.url);
|
||||
|
|
|
|||
13
src/utils/body.ts
Normal file
13
src/utils/body.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { H3Event } from 'h3';
|
||||
|
||||
export function hasBody(event: H3Event) {
|
||||
const method = event.method.toUpperCase();
|
||||
return ['PUT', 'POST', 'PATCH', 'DELETE'].includes(method);
|
||||
}
|
||||
|
||||
export async function getBodyBuffer(
|
||||
event: H3Event,
|
||||
): Promise<Buffer | undefined> {
|
||||
if (!hasBody(event)) return;
|
||||
return await readRawBody(event, false);
|
||||
}
|
||||
|
|
@ -1,11 +1,10 @@
|
|||
import { H3Event, EventHandlerRequest } from 'h3';
|
||||
|
||||
export function sendJson(ops: {
|
||||
export async function sendJson(ops: {
|
||||
event: H3Event<EventHandlerRequest>;
|
||||
data: Record<string, any>;
|
||||
status?: number;
|
||||
}) {
|
||||
setResponseStatus(ops.event, ops.status ?? 200);
|
||||
appendResponseHeader(ops.event, 'content-type', 'application/json');
|
||||
send(ops.event, JSON.stringify(ops.data, null, 2));
|
||||
await send(ops.event, JSON.stringify(ops.data, null, 2), 'application/json');
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue