@@ -4,23 +4,23 @@ import { NextRequest } from 'next/server';
44export async function POST ( request : NextRequest ) {
55 try {
66 // 运行时动态确定后端地址
7- const backendUrl = process . env . NEXT_PUBLIC_API_URL
7+ const backendUrl = process . env . NEXT_PUBLIC_API_URL
88 ? process . env . NEXT_PUBLIC_API_URL . replace ( '/api' , '' ) // 移除 /api 后缀
99 : process . env . BACKEND_URL || 'http://localhost:8080' ;
1010
1111 const targetUrl = `${ backendUrl } /api/chat` ;
12-
12+
1313 // 获取请求体
1414 const body = await request . text ( ) ;
15-
15+
1616 // 转发请求到实际后端
1717 const response = await fetch ( targetUrl , {
1818 method : 'POST' ,
1919 headers : {
2020 'Content-Type' : 'application/json' ,
2121 // 转发其他相关头
2222 ...( request . headers . get ( 'authorization' ) && {
23- ' authorization' : request . headers . get ( 'authorization' ) !
23+ authorization : request . headers . get ( 'authorization' ) ! ,
2424 } ) ,
2525 } ,
2626 body,
@@ -29,13 +29,10 @@ export async function POST(request: NextRequest) {
2929 // 检查响应是否成功
3030 if ( ! response . ok ) {
3131 console . error ( `Backend API error: ${ response . status } ${ response . statusText } ` ) ;
32- return new Response (
33- JSON . stringify ( { error : 'Backend API error' , status : response . status } ) ,
34- {
35- status : response . status ,
36- headers : { 'Content-Type' : 'application/json' }
37- }
38- ) ;
32+ return new Response ( JSON . stringify ( { error : 'Backend API error' , status : response . status } ) , {
33+ status : response . status ,
34+ headers : { 'Content-Type' : 'application/json' } ,
35+ } ) ;
3936 }
4037
4138 // 转发响应,保持流式传输
@@ -46,25 +43,24 @@ export async function POST(request: NextRequest) {
4643 'Content-Type' : response . headers . get ( 'content-type' ) || 'application/json' ,
4744 // 保持流式传输的头
4845 ...( response . headers . get ( 'transfer-encoding' ) && {
49- 'Transfer-Encoding' : response . headers . get ( 'transfer-encoding' ) !
46+ 'Transfer-Encoding' : response . headers . get ( 'transfer-encoding' ) ! ,
5047 } ) ,
5148 // CORS 头(如果需要)
5249 'Access-Control-Allow-Origin' : '*' ,
5350 'Access-Control-Allow-Methods' : 'POST, OPTIONS' ,
5451 'Access-Control-Allow-Headers' : 'Content-Type, Authorization' ,
5552 } ,
5653 } ) ;
57-
5854 } catch ( error ) {
5955 console . error ( 'API proxy error:' , error ) ;
6056 return new Response (
61- JSON . stringify ( {
62- error : 'Internal proxy error' ,
63- message : error instanceof Error ? error . message : 'Unknown error'
64- } ) ,
65- {
57+ JSON . stringify ( {
58+ error : 'Internal proxy error' ,
59+ message : error instanceof Error ? error . message : 'Unknown error' ,
60+ } ) ,
61+ {
6662 status : 500 ,
67- headers : { 'Content-Type' : 'application/json' }
63+ headers : { 'Content-Type' : 'application/json' } ,
6864 }
6965 ) ;
7066 }
@@ -80,4 +76,4 @@ export async function OPTIONS() {
8076 'Access-Control-Allow-Headers' : 'Content-Type, Authorization' ,
8177 } ,
8278 } ) ;
83- }
79+ }
0 commit comments