Spaces:
Runtime error
Runtime error
Create src/app/api/proxy/[...path]/route.ts
Browse files
src/app/api/proxy/[...path]/route.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { NextRequest, NextResponse } from 'next/server';
|
| 2 |
+
|
| 3 |
+
const BACKEND = 'http://localhost:8000';
|
| 4 |
+
|
| 5 |
+
async function handler(req: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
|
| 6 |
+
const { path } = await params;
|
| 7 |
+
const backendPath = path.join('/');
|
| 8 |
+
const search = req.nextUrl.search || '';
|
| 9 |
+
const url = `${BACKEND}/${backendPath}${search}`;
|
| 10 |
+
|
| 11 |
+
const headers = new Headers();
|
| 12 |
+
req.headers.forEach((value, key) => {
|
| 13 |
+
if (!['host', 'connection'].includes(key.toLowerCase())) {
|
| 14 |
+
headers.set(key, value);
|
| 15 |
+
}
|
| 16 |
+
});
|
| 17 |
+
|
| 18 |
+
try {
|
| 19 |
+
const body = req.method !== 'GET' && req.method !== 'HEAD' ? await req.arrayBuffer() : undefined;
|
| 20 |
+
const res = await fetch(url, {
|
| 21 |
+
method: req.method,
|
| 22 |
+
headers,
|
| 23 |
+
body: body ? Buffer.from(body) : undefined,
|
| 24 |
+
});
|
| 25 |
+
|
| 26 |
+
const responseHeaders = new Headers();
|
| 27 |
+
res.headers.forEach((value, key) => {
|
| 28 |
+
responseHeaders.set(key, value);
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
return new NextResponse(res.body, {
|
| 32 |
+
status: res.status,
|
| 33 |
+
headers: responseHeaders,
|
| 34 |
+
});
|
| 35 |
+
} catch {
|
| 36 |
+
return NextResponse.json({ error: 'Backend unavailable' }, { status: 503 });
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
export const GET = handler;
|
| 41 |
+
export const POST = handler;
|
| 42 |
+
export const PUT = handler;
|
| 43 |
+
export const DELETE = handler;
|
| 44 |
+
export const PATCH = handler;
|