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

解决Flask框架CORS Policy错误及flask_cors模块缺失问题

解决WordPress插件表单提交Flask应用的CORS及模块缺失问题

一、先解决flask_cors no module named错误

这是因为PythonAnywhere虚拟环境中未正确安装flask-cors包,按以下步骤操作:

  1. 登录PythonAnywhere控制台,激活对应虚拟环境:
    source /home/你的用户名/.virtualenvs/你的虚拟环境名/bin/activate
    
  2. 执行安装命令:
    pip install flask-cors
    
  3. 回到PythonAnywhere的Web面板,确认Virtualenv字段已正确填写虚拟环境路径(如/home/你的用户名/.virtualenvs/你的虚拟环境名),然后重启Web应用。

二、修正Flask代码中的语法错误

你的article.py里变量名不符合Python规范(不能以数字开头),会导致代码运行失败,进而服务无法正常响应请求:

from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 允许所有源跨域请求

@app.route('/submit', methods=['POST'])
def submit_data():
    one_key = request.form.get('one')
    two_key = request.form.get('two')
    three_key = request.form.get('three')

    # 这里添加数据保存逻辑(如写入数据库/文件)

    return 'Veriler başarıyla alındı.'

if __name__ == '__main__':
    app.run(port=8081)

三、修正前端Fetch请求配置

  1. 统一URL协议:错误信息显示请求地址为https://metehanz.pythonanywhere.com/submit,但前端代码写的是http://username.pythonanywhere.com/submit,改为HTTPS协议:
    fetch("https://metehanz.pythonanywhere.com/submit", {
        method: "POST",
        body: formData
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(data => {
            console.log(data);
            // 成功响应后的操作写在这里
        })
        .catch(error => {
            console.error('Fetch操作出错:', error);
        });
    
  2. 若仍有CORS问题,可精确配置允许跨域的源(仅允许你的WordPress域名):
    CORS(app, origins="http://deneme.local")
    

四、验证服务状态

修改代码后重启PythonAnywhere的Web应用,通过以下方式排查:

  • 检查Web面板的"Logs"选项,查看是否有代码运行错误;
  • 直接访问https://metehanz.pythonanywhere.com/submit(GET方法),若返回405 Method Not Allowed则说明服务正常启动(接口仅接受POST请求)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:42:47