Flask跨端口REST API调用报403:浏览器可访问脚本无法访问
Hey there! Let's tackle this 403 error you're hitting when calling your Flask app on localhost:1112 from localhost:1111 using the requests library. Since the browser can access the API just fine, the issue is almost certainly related to how programmatic requests are handled vs. browser requests. Here are the most common fixes to try:
Even though both apps are on localhost, different ports count as separate origins. Flask doesn't handle cross-origin requests by default, and while browsers automatically send an Origin header that might be allowed, your requests call might not be including it—or the 1112 app isn't configured to accept requests from 1111.
- Fix: Install and configure
flask-corson the 1112 app:
Then update your 1112 app code:pip install flask-corsfrom flask import Flask from flask_cors import CORS app = Flask(__name__) # Allow requests specifically from localhost:1111 (use "*" only for testing, not production) CORS(app, origins="http://localhost:1111") # Your API routes go here
If your 1112 app uses Flask-WTF or similar extensions for CSRF protection, it will block requests that don't include a valid CSRF token. Browsers automatically handle this via cookies, but requests doesn't send the token unless you explicitly include it.
- Option 1: Exempt your API route from CSRF protection (if it doesn't need it):
from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect(app) @app.route("/your-target-api", methods=["POST"]) @csrf.exempt def your_api_endpoint(): # Your API logic here - Option 2: Fetch the CSRF token from the 1112 app's cookie and include it in your request:
import requests # First get the CSRF token from the 1112 app's cookie init_response = requests.get("http://localhost:1112") csrf_token = init_response.cookies.get("csrf_token") # The cookie name might vary—check your app's config # Include the token in headers for your API call headers = {"X-CSRFToken": csrf_token} api_response = requests.post( "http://localhost:1112/your-target-api", headers=headers, json={"key": "value"} # Your payload here )
Use your browser's dev tools (Network tab) to inspect the exact headers sent when accessing the 1112 API. Your requests call might be missing key headers like User-Agent or Accept that the app expects.
- Example of replicating browser headers:
headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36", "Accept": "application/json, text/plain, */*" } response = requests.get("http://localhost:1112/your-target-api", headers=headers)
If your 1112 app has any custom middleware for IP whitelisting or access control, double-check that it allows requests from 127.0.0.1 (localhost). Some middleware blocks non-browser requests even from the same machine.
If none of these fix the issue, share the exact error message from the 1112 app's logs—it'll help narrow down the problem further!
内容的提问来源于stack exchange,提问作者Sourav

