最简单的Vercel反向代理http请求

vercel.json:

{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "rewrites": [
    { "source": "/api/(.*)", "destination": "/api/index.py" }
  ]
}

api/index.py:

import urllib.request
import urllib.error
from http.server import BaseHTTPRequestHandler
import json

class handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self._proxy_request()
    
    def do_POST(self):
        self._proxy_request()
    
    def do_PUT(self):
        self._proxy_request()
    
    def do_DELETE(self):
        self._proxy_request()
    
    def do_PATCH(self):
        self._proxy_request()
    
    def do_OPTIONS(self):
        self._proxy_request()
    
    def _proxy_request(self):
        try:
            # 构建目标URL
            target_host = "被代理ip"
            target_url = f"http://{target_host}{self.path}"
            
            # 读取请求体(如果有)
            content_length = int(self.headers.get('Content-Length', 0))
            post_data = None
            if content_length > 0:
                post_data = self.rfile.read(content_length)
            
            # 创建请求
            req = urllib.request.Request(
                target_url,
                data=post_data,
                method=self.command
            )
            
            # 复制请求头(排除一些不需要的)
            for header, value in self.headers.items():
                if header.lower() not in ['host', 'content-length']:
                    req.add_header(header, value)
            
            # 发送请求
            with urllib.request.urlopen(req) as response:
                # 设置响应状态码
                self.send_response(response.status)
                
                # 复制响应头
                for header, value in response.headers.items():
                    if header.lower() not in ['connection', 'transfer-encoding']:
                        self.send_header(header, value)
                
                self.end_headers()
                
                # 复制响应体
                self.wfile.write(response.read())
                
        except urllib.error.HTTPError as e:
            # 处理HTTP错误
            self.send_response(e.code)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            error_response = json.dumps({
                "error": "Proxy Error",
                "status": e.code,
                "message": str(e.reason)
            }).encode('utf-8')
            self.wfile.write(error_response)
            
        except Exception as e:
            # 处理其他错误
            self.send_response(500)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            error_response = json.dumps({
                "error": "Internal Server Error",
                "message": str(e)
            }).encode('utf-8')
            self.wfile.write(error_response)
posted @ 2025-09-11 16:20  qiao39gs  阅读(71)  评论(0)    收藏  举报