Flask应用仅在浏览器中出现CORS错误,求排查原因
问题原因及解决办法
核心原因1:Flask端CORS处理冲突
你同时使用了flask-cors的CORS(app)自动处理CORS,又手动定义了OPTIONS /process_url路由,两者逻辑冲突导致预请求(OPTIONS)返回的CORS头不完整。
flask-cors已经会自动为所有路由生成符合标准的OPTIONS响应,包含Access-Control-Allow-Origin等必要头。- 手动编写的
handle_preflight函数返回的响应缺少关键的Access-Control-Allow-Origin头(make_default_options_response不会自动添加这个头),浏览器因此拒绝后续的POST请求。
核心原因2:Content Script的同源限制
Content Script运行在当前网页的上下文环境中,即使你在manifest.json里声明了对http://localhost:5000/*的权限,它发起的XHR请求依然受当前网页的同源策略约束。只有扩展的Background Script属于独立上下文,不受网页同源限制,且已拥有权限。
修复步骤
步骤1:修复Flask代码
删除手动定义的OPTIONS路由及处理函数,让flask-cors自动处理所有预请求:
import logging from flask import Flask, request from flask_cors import CORS app = Flask(__name__) CORS(app) logging.getLogger('flask_cors').level = logging.DEBUG @app.route('/headers', methods=['GET', 'POST']) def headers(): return dict(request.headers) @app.route('/process_url', methods=['POST']) def process_url(): print("processing") print(request.headers) url = request.form.get('url') # Process the URL here return dict(request.headers) if __name__ == '__main__': app.run()
步骤2:修改Chrome扩展,用Background Script发起请求
修改content.js,改为向Background发送消息:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.action === "sendRequest") { var currentUrl = window.location.href; chrome.runtime.sendMessage({action: "callApi", url: currentUrl}, function(response) { sendResponse(response); }); return true; } });
修改background.js,添加请求处理逻辑:
chrome.contextMenus.create({ title: "Send Request", contexts: ["page"], onclick: function(info, tab) { chrome.tabs.sendMessage(tab.id, { action: "sendRequest" }); } }); chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.action === "callApi") { const xhr = new XMLHttpRequest(); xhr.open("POST", "http://localhost:5000/process_url", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { xhr.status === 200 ? sendResponse(xhr.responseText) : sendResponse({error: '请求失败'}); } }; xhr.send("url=" + encodeURIComponent(request.url)); return true; } });
补充说明
cURL调用无异常是因为它是命令行工具,不会执行浏览器的同源策略检查,无论CORS头是否完整,都会正常发送请求并接收响应。
内容的提问来源于stack exchange,提问作者Huey
相关产品推荐
相关产品推荐

