You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FLASK+VUE跨域问题:预检请求未通过HTTP状态校验求助

解决Flask+Vue跨域CORS预检请求失败问题

问题现象

跨域请求时触发CORS拦截,报错信息如下:

Blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

最终请求失败提示:

Access to fetch at 'http://localhost:8000/api/v1/ports/getports' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
GET http://localhost:8000/api/v1/ports/getports net::ERR_FAILED
Failed to Fetch

注:Postman调用目标路由正常,仅前端请求失败

相关代码

前端myFetch.ts

const API_ROOT = import.meta.env.VITE_API_ROOT as string;

export function rest(url: string, body?: unknown, method?: string, headers?: HeadersInit){

    return fetch(url, {
        method: method ?? (body ? "POST" : "GET"),
        headers: {
            'Content-Type': 'application/json',
            ...headers
        },
        body: body ? JSON.stringify(body) : undefined
    })
        .then(response => response.ok 
            ? response.json()
            : response.json().then(err => Promise.reject(err))    )
}

export function api(action: string, body?: unknown, method?: string, headers?: HeadersInit){
    return rest(`${API_ROOT}/${action}`, body, method, headers);
}

后端Flask基础配置(app.py)

已添加全局CORS配置:

CORS(app)

已尝试但无效的解决方法

  • 手动通过after_request设置CORS响应头:
    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', 'http://localhost:5173')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Methods', 'OPTIONS, GET')
        response.headers.add('Access-Control-Allow-Credentials', 'true')
        return response
    
  • 为目标路由添加@cross_origin装饰器:
    @cross_origin(origin="http://localhost:5173", supports_credentials=True)
    
  • 在前端rest函数中手动处理OPTIONS请求方法:
    const actualMethod = method === "OPTIONS" ? "OPTIONS" : method ?? (body ? "POST" : "GET");
    

最终解决思路

问题根源在于Flask未正确处理浏览器发送的OPTIONS预检请求,导致预检请求返回非200的状态码,触发CORS拦截。

具体修复方案:

  1. 确保蓝图路由支持OPTIONS方法:如果使用了Flask蓝图,直接为蓝图单独配置CORS,确保预检请求能被正确响应:
    from flask_cors import CORS
    # 假设你的蓝图实例为api_bp
    CORS(api_bp)
    
  2. 检查URL斜杠配置:若开启了strict_slashes=True,可能导致OPTIONS请求因URL格式问题被重定向(返回3xx状态码),需确保请求URL与路由定义的格式一致,或关闭严格斜杠检查。
  3. 排除中间件拦截:如果路由添加了权限验证等中间件,需确保OPTIONS请求能绕过这些验证,直接返回200状态码,比如在中间件中判断请求方法为OPTIONS时直接放行。
  4. 验证flask-cors版本:确保使用的flask-cors扩展为最新版本,避免版本兼容问题导致的配置失效。

内容的提问来源于stack exchange,提问作者Lara-Codes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 23:20:36