yuoop commited on
Commit
6145430
·
verified ·
1 Parent(s): 0f07b0d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -9
app.py CHANGED
@@ -18,9 +18,7 @@ def proxy(path):
18
  try:
19
  # 构造请求头
20
  headers = dict(request.headers)
21
- # 删除 Host 头,防止目标服务器出错
22
  headers.pop('Host', None)
23
- # 删除 Content-Length,让 requests 自动处理
24
  headers.pop('Content-Length', None)
25
 
26
  # 发送请求
@@ -28,24 +26,29 @@ def proxy(path):
28
  method=request.method,
29
  url=target_url,
30
  headers=headers,
31
- data=request.get_data(), # 获取原始请求体
32
- stream=True, # 使用流式传输,处理大文件
33
- allow_redirects=False # 禁止重定向,让客户端处理
34
  )
35
 
36
  # 获取响应内容的编码,默认使用 UTF-8
37
  encoding = response.encoding or 'utf-8'
38
- content = response.content.decode(encoding, errors='replace') # 解码并替换无法解码的字符
39
 
40
  # 构造响应
41
  excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
42
  response_headers = [(name, value) for (name, value) in response.headers.items()
43
  if name.lower() not in excluded_headers]
44
 
 
 
 
 
 
 
 
45
  proxy_response = Response(content, response.status_code, headers=response_headers)
46
-
47
- # 设置 Content-Type,确保客户端正确解析
48
- proxy_response.headers['Content-Type'] = f'text/plain; charset={encoding}'
49
 
50
  # 添加 CORS 头
51
  proxy_response.headers['Access-Control-Allow-Origin'] = '*'
 
18
  try:
19
  # 构造请求头
20
  headers = dict(request.headers)
 
21
  headers.pop('Host', None)
 
22
  headers.pop('Content-Length', None)
23
 
24
  # 发送请求
 
26
  method=request.method,
27
  url=target_url,
28
  headers=headers,
29
+ data=request.get_data(),
30
+ stream=True,
31
+ allow_redirects=False
32
  )
33
 
34
  # 获取响应内容的编码,默认使用 UTF-8
35
  encoding = response.encoding or 'utf-8'
36
+ content = response.content.decode(encoding, errors='replace')
37
 
38
  # 构造响应
39
  excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
40
  response_headers = [(name, value) for (name, value) in response.headers.items()
41
  if name.lower() not in excluded_headers]
42
 
43
+ # 检查原始响应的 Content-Type,如果包含 json,则设置为 application/json
44
+ original_content_type = response.headers.get('Content-Type', 'text/plain')
45
+ if 'application/json' in original_content_type.lower():
46
+ content_type = 'application/json; charset=utf-8'
47
+ else:
48
+ content_type = f'text/plain; charset={encoding}'
49
+
50
  proxy_response = Response(content, response.status_code, headers=response_headers)
51
+ proxy_response.headers['Content-Type'] = content_type
 
 
52
 
53
  # 添加 CORS 头
54
  proxy_response.headers['Access-Control-Allow-Origin'] = '*'