Flask中仅修改域名重定向带Payload的POST请求方法
Hey there! I’ve run into exactly this issue before—Flask’s default redirect() function converts POST requests to GET, which drops your payload entirely. The trick here is to use a 307 Temporary Redirect instead, which tells browsers to preserve the original request method and payload while only changing the domain. Here’s how to implement it easily:
Basic Implementation
You can directly construct a 307 response using Flask’s make_response() method, setting the Location header to your target domain plus the original request path and query parameters.
from flask import Flask, request, make_response app = Flask(__name__) @app.route('/<path:path>', methods=['POST']) def redirect_post_requests(path): # Replace with your target domain target_domain = "https://your-new-domain.com" # Build the full target URL: new domain + original path + original query params target_url = f"{target_domain}/{path}?{request.query_string.decode('utf-8')}" # Create 307 response response = make_response() response.status_code = 307 response.headers['Location'] = target_url return response
Why 307?
Unlike the standard 302 redirect, 307 enforces the browser to reuse the original request method (POST) and payload when following the redirect. This is exactly what you need to keep the POST data intact while switching domains.
Reusable Decorator (For Cleaner Code)
If you need this logic across multiple endpoints, wrap it in a decorator to avoid repeating code:
from flask import request, make_response def redirect_post_to(target_domain): def decorator(func): def wrapper(*args, **kwargs): # Get original path (strip leading slash to avoid double slashes) original_path = request.path.lstrip('/') # Build full target URL target_url = f"{target_domain}/{original_path}?{request.query_string.decode('utf-8')}" # Return 307 redirect response = make_response() response.status_code = 307 response.headers['Location'] = target_url return response return wrapper return decorator # Use the decorator on any POST endpoint @app.route('/api/submit-form', methods=['POST']) @redirect_post_to("https://api.new-domain.com") def submit_form(): # No need for extra logic here—the decorator handles the redirect pass
Important Notes
- CORS Considerations: If your frontend is making cross-origin requests, ensure the target domain has proper CORS headers configured. Browsers might block the redirected POST request otherwise.
- Permanent Redirect: If you need a permanent redirect (instead of temporary), use status code 308 Permanent Redirect—it works the same way as 307 but signals the redirect is permanent.
- Testing: Verify with tools like Postman or curl. For example:
Check the response headers for thecurl -X POST -d "username=test&password=123" http://localhost:5000/api/submit-form -vLocationfield, and confirm the subsequent request includes the original payload.
内容的提问来源于stack exchange,提问作者Oliver Blue

