You need to enable JavaScript to run this app. 使用FlaskWTF时跨域AJAX POST请求被识别为匿名返回401未授权
优惠活动
大模型
产品
解决方案
定价
更多

使用FlaskWTF时跨域AJAX POST请求被识别为匿名返回401未授权

修复步骤

1. 修正前端请求配置

原jQuery AJAX缺凭证配置

jQuery跨域请求默认不携带Cookie,需显式开启,在ajax配置块中新增两行参数:

$.ajax({
    type: "POST",
    url:  "http://localhost:5000/predict",
    data: img,
    xhrFields: { withCredentials: true }, // 新增:携带跨域Cookie
    crossDomain: true, // 新增:标记跨域请求
    success: function(data){
        $('#result').text('Predicted Output: ' + data);
    }
});

改写的fetch请求参数错误

fetch的POST请求需用body传数据,请求头要放在headers字段中,顶层ContentType属性不生效,修正后代码:

fetch("http://localhost:5000/predict", {
  method: "POST",
  body: img, // 原代码误写为data
  headers: {
    'Content-Type': 'application/json' // 放入headers配置
  },
  credentials: 'include'
})
// 需先解析响应为文本,否则拿到的是原始Response对象
.then(res => res.text())
.then(function(data) {
  $('#result').text('Predicted Output: ' + data);
}).catch((err) => {
  console.log(err)
});

2. 修正后端CORS配置

  • 路由装饰器的origin参数不能只写localhost,需填写带协议、端口的完整前端地址(比如前端跑在http://localhost:3000就填这个值),开启凭证模式后不能用*通配符,需写明确的地址白名单:
@app.route('/predict', methods=['GET','POST'])
@login_required
@cross_origin(
    origins=["http://localhost:3000"], # 替换为前端实际运行的完整地址
    headers=['Content-Type', 'Authorization'],
    supports_credentials=True
)
def predict():
  • 不要同时在全局CORS(app)和单个路由上重复配置@cross_origin,两者叠加易引发配置冲突,建议二选一:要么全局统一配置CORS,要么仅在需跨域的路由上单独配置。

3. 补充Session Cookie跨域配置

跨域场景下Flask默认的Session Cookie的SameSite属性会被浏览器拦截,需在app初始化后新增配置:

app = Flask(__name__)
app.config['SESSION_COOKIE_SAMESITE'] = 'None'
app.config['SESSION_COOKIE_SECURE'] = False # 本地http测试设为False,上线需改为True

高版本Chrome在http协议下会拒绝SameSite=None的Cookie,临时测试可直接让Flask托管前端静态文件,前后端跑在同一端口(同源无跨域Cookie问题)。


内容的提问来源于stack exchange,提问作者famousKid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 20:06:03