简体   繁体   中英

How do I get rid of this error 405 ? (Flask/Py)

I want to make a chat application with Flask and socket.io, but I keep getting an error 405 whenever I click on "send". I've been trying to make this work, but it just won't (just a basic thing with a username and a message). Here is what the error says:

"Method Not Allowed The method is not allowed for the requested URL."

I don't really know what's wrong. When I check my cmd, I see:

POST / HTTP/1.1" 405 362 0.001000 127.0.0.1 - - [28/May/2021 16:44:29] "GET /socket.io/?EIO=3&transport=websocket&sid=7392cec39d5841bcaa7d7c8faaa1b6fb HTTP/1.1" 200 0 3.134387

main.py:

from flask import Flask, render_template #Importation du modèle flask et de render_template
from flask_socketio import SocketIO #Importation du modèle socketio

app = Flask(__name__)
app.config['SECRET_KEY'] =b'\xba!\xe3];\xce\xe6V}\x1d\xee\xda\x03\x8b\xbfS\xb9\x0fE\x8f\x15\x98O\x92' #Clé secrète afin de garder la partie client sécurisée
socketio = SocketIO(app)


@app.route('/')
def index(): #Définition de la fonction index
    return render_template('index.html') #Affichage de la page index.html


def messageReceived(methods=['GET', 'POST']): #Définition de la fonction message reçu
    print('Message reçu')


@socketio.on('my event') 
def handle_my_custom_event(json, methods=['GET', 'POST']): #Définition de la fonction message envoyé
    print('Mon événement a été reçu: ' + str(json))
    socketio.emit('Ma réponse', json, callback=messageReceived) #Émission du message


if __name__ == '__main__':      #Boucle permettant à l'application web de continuer de fonctionner à l'infinie
    socketio.run(app, debug=True)

index.html:

<!DOCTYPE html>
<html lang="fr">
    <head>
        <meta charset="utf-8">
        <title>Chat Flask</title>
        <link rel="stylesheet" href="{{url_for('static', filename='index.css')}}">
    </head>
    <body>
        <p id="para1" style='color: #9cd374;font-size: 30px;'>Pas de message...</p>
        <div class="message_holder"></div>
        <form action="" method="POST">
            <div class="inputs">
            <input type="text" id="username" placeholder="Nom d'utilisateur"/>
            <input type="text" id="message" placeholder="Message"/>
            <input type="image" id="send" src="static/send.png"/> 
                <!-- Utilisation direct du <style> car le css ne fonctionne pas pour les entrées -->
                <style>
      input[type="email"] {
        text-align: center;
      }
      input[type="text"] {
        text-align: right;
      }
      input[type="tel"] {
        text-align: left;
      }
      body {
        text-align: center;
      }
      label {
        display: block;
        margin-bottom: 30px;
      }
    </style>
            </div>
        </form>
        <!-- Script JS nécessaire pour utiliser socketIO -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
        <script type="text/javascript">
            var socket;
            $(document).ready(function(){
                socket = io.connect('http://' + document.domain + ':' + location.port + '/chat');
                socket.on('connect', function() {
                    socket.emit('joined', {});
                });
                socket.on('status', function(data) {
                    $('#chat').val($('#chat').val() + '<' + data.msg + '>\n');
                    $('#chat').scrollTop($('#chat')[0].scrollHeight);
                });
                socket.on('message', function(data) {
                    $('#chat').val($('#chat').val() + data.msg + '\n');
                    $('#chat').scrollTop($('#chat')[0].scrollHeight);
                });
                $('#text').keypress(function(e) {
                    var code = e.keyCode || e.which;
                    if (code == 13) {
                        text = $('#text').val();
                        $('#text').val('');
                        socket.emit('text', {msg: text});
                    }
                });
            });
      </script>
    </body>
</html>

It seems you were using this blog: https://codeburst.io/building-your-first-chat-application-using-flask-in-7-minutes-f98de4adfa5d

At first you should try to follow the guide without any modifications. When you have a working solution, then you can make small adjustments, one by one and always check if it still works, until you are confident using the technology.

Some problem that I see at first glance:

  • io.connect('http://' + document.domain + ':' + location.port + '/chat'); but on your server, you have defined it without path, so you should only use domain + port: 'http://' + document.domain + ':' + location.port
  • You have defined what type of messages you are listening to on server side: @socketio.on('my event') , but you are sending different events in JavaScript: socket.emit('joined', {});
  • The same goes for the other direction. On the server you are emitting events to client-side with type socketio.emit('Ma réponse', ... , but on the client side you are listening to events like: socket.on('status', ...

To address the main question: your route / only accepts GET requests by default. If you want to allow POST requests, you should adapt this line like this:

@app.route('/')
def index(methods=['GET', 'POST']):

You may need to do the same in other functions.

It will be a great help if you could paste the entire log but after I saw your index.html, I think you ran into the very same problem as mine.

In your index.html, you used pretty old socket io JS client (1.3.6):

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>

Maybe you look closely in the terminal, it said (which you omitted):

"The client is using an unsupported version of the Socket.IO or Engine.IO protocols (further occurrences of this error will be logged with level INFO)"

To solve this, please refer to this table that is available on flask-socketio installation guide page :

flask-socketio 兼容性表

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM