首页 > 解决方案 > 尝试 POST 到 Flask 应用程序时出现 HTTP 405 错误

问题描述

当我尝试从我的 Web 表单向我的烧瓶应用程序提交请求时,我得到一个不允许的 HTTP 405 方法。


app.py(Python 应用程序代码):

# app.py
from flask import Flask, render_template, request, redirect, json, url_for
from flaskext.mysql import MySQL
app = Flask(__name__)

# Database connection info. Note that this is not a secure connection.
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'RamsterDB'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql = MySQL()
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()

mysql = MySQL()
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()

@app.route('/')
def main():
    return render_template('search.html')

@app.route('/showRegister', methods=['POST','GET'])
def showRegister():
    return render_template('register.html')

@app.route('/register', methods=['POST, GET'])
def register():
     # read the posted values from the UI
    #try:
        _username = request.form['inputUsername']
        _password = request.form['inputPassword']

     # validate the received values
        if _username and _password:
            return json.dumps({'html': '<span>All fields good !!</span>'})
        else:
            return json.dumps({'html': '<span>Enter the required fields</span>'})

    #return render_template('register.html')

if __name__ == '__main__':
    app.debug = True
    app.run()

register.html(注册页面代码):

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Ramster</title>
    <link rel="stylesheet" href="/static/index.css">
    <script src="/static/js/jquery-1.11.2.js"></script>
    <script src="../static/js/register.js"></script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, height=100%">
</head>

<body>
    <div class="topnav">
        <a href="login">Login</a>
        <a href="#">Register</a>
    </div>

    <div class="content">
        <h2>Ramster</h2>
        <p>Register your team</p>
        <form class="example" method="post" action="" style="margin:left;max-width:600px">
        <input type="text" name="inputUsername" id="inputUsername" placeholder="Username" required autofocus><br><br><br>
        <input type="text" name="inputPassword" id="inputPassword" placeholder="Password" required><br><br><br>
        <button id="btnRegister" class="example" type="submit">Register</button>
        </form>
        <!--<form class="example" method="post" action="" style="margin:left;max-width:600px">
            <input type="text" placeholder="Username" name="inputUsername">
            <input type="text" placeholder="Password" name="inputPassword">
                    <button type="submit">Register</button>
                </form>
                <p></p>-->
    </div>
    <div class="footer">
        <p>Terms and Conditions</p>
    </div>

</body>

</html>

注册.js:

$(function() {
    $('#btnRegister').click(function() {

        $.ajax({
            url: '/register',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});

浏览器中的错误:

jquery-1.11.2.js:9659 POST http://localhost:5000/register 405 (METHOD NOT ALLOWED)

我曾尝试更改表单参数以及 Python 代码,但似乎没有任何效果。在解决 405 问题之前,我还没有尝试连接到 MySQL。我试图找到答案,但在任何地方都找不到。

标签: pythonformshttpflaskpost

解决方案


您有一个包含单个元素的列表,而不是包含两个元素的列表。代替

@app.route('/register', methods=['POST, GET'])

@app.route('/register', methods=['POST', 'GET'])

推荐阅读