You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Flask应用遭CORS策略拦截求助:无Access-Control-Allow-Origin头

Fixing CORS Issues When Rendering Downloaded Web Pages in Flask

I see the issue here—your CORS problem isn't actually coming from your Flask backend, even though you tried using flask_cors. Let me break this down and show you how to fix it:

Why flask_cors Isn't Helping

The error message you're seeing:

来自源http://127.0.0.1:5000的请求已被CORS策略阻止:请求的资源上不存在Access-Control-Allow-Origin头

is not about your frontend talking to your Flask server—it's about your browser trying to load third-party resources (like CSS, images, or JS) from the original website directly. Those external servers don't include the Access-Control-Allow-Origin header for http://127.0.0.1:5000, so the browser blocks the request. flask_cors only handles cross-origin requests to your Flask API, not requests to external sites.

Instead of letting the browser request external resources directly, create a Flask route that acts as a proxy. Your browser will ask your Flask server for the resource, and your server will fetch it from the original site and return it—this avoids cross-domain issues entirely.

Step 1: Add a Proxy Route

Add this to your Flask app:

import urllib.parse

@app.route("/proxy")
def proxy():
    resource_url = request.args.get("url")
    if not resource_url:
        return "Missing resource URL", 400
    
    # Fetch the resource from the original site
    try:
        response = requests.get(resource_url, headers={"User-Agent":"Chrome/42.0.2311.135"})
        # Return the resource with the same headers/content type
        return response.content, response.status_code, response.headers.items()
    except Exception as e:
        return f"Failed to fetch resource: {str(e)}", 500

In your /crop route, instead of pointing resources to the original URL, rewrite them to use your proxy. For example:

# Replace your existing link processing code with this
for a in soup.findAll("link", attrs={'href':True}, rel="stylesheet"):
    original_href = a['href']
    if original_href.startswith(('http://', 'https://')):
        proxy_url = f"/proxy?url={urllib.parse.quote(original_href)}"
        a['href'] = proxy_url
    else:
        # Handle relative links by resolving to full URL first
        dom = urlparse(link)
        full_url = f"{dom.scheme}://{dom.netloc}{original_href}"
        proxy_url = f"/proxy?url={urllib.parse.quote(full_url)}"
        a['href'] = proxy_url

Do the same for <script> tags with src attributes, <img> tags, and any other external resources in the HTML.

Solution 2: Download All Resources Locally

Another approach is to download every external resource (CSS, JS, images) to your server's filesystem, then rewrite the HTML links to point to these local files. This way, the browser only loads resources from your Flask server, no cross-domain requests needed.

Example Modification for CSS Files

import os

# Create a directory to store downloaded resources
resource_dir = os.path.join(dir, "static", "downloaded_resources")
os.makedirs(resource_dir, exist_ok=True)

for a in soup.findAll("link", attrs={'href':True}, rel="stylesheet"):
    original_href = a['href']
    if not original_href.startswith(('http://', 'https://')):
        dom = urlparse(link)
        original_href = f"{dom.scheme}://{dom.netloc}{original_href}"
    
    # Download the CSS file
    try:
        css_response = requests.get(original_href, headers={"User-Agent":"Chrome/42.0.2311.135"})
        if css_response.status_code == 200:
            # Generate a unique filename for the resource
            filename = os.path.basename(urlparse(original_href).path)
            file_path = os.path.join(resource_dir, filename)
            with open(file_path, 'wb') as f:
                f.write(css_response.content)
            # Rewrite the link to point to the local file
            a['href'] = f"/static/downloaded_resources/{filename}"
    except Exception as e:
        print(f"Failed to download {original_href}: {str(e)}")

Solution 3: Disable Browser CORS (Only for Testing!)

If you're just testing locally and don't want to set up a proxy or download resources, you can launch your browser with CORS disabled. Never do this for regular browsing or production use—it's a security risk.

For Chrome on Windows:

chrome.exe --disable-web-security --user-data-dir="C:/ChromeDevSession"

For Chrome on macOS:

open -n -a "Google Chrome" --args --disable-web-security --user-data-dir="/tmp/ChromeDevSession"

内容的提问来源于stack exchange,提问作者Syed Bilal Ali

火山引擎 最新活动