Flask server responding with "Method Not Allowed" error for POST request to "/predict" endpoint

32 Views Asked by At

I have a Flask server with an endpoint "/predict" configured to handle POST requests. However, when I send a POST request to this endpoint from my frontend, the server responds with a "Method Not Allowed" error (HTTP status code 405). The frontend code is correctly sending a POST request, and CORS is configured properly. I expect the server to accept the POST request and return a response with the predicted result.

Failed to load resource: the server responded with a status of 405 (Method Not Allowed) chatbot.js:65 Error: SyntaxError: Unexpected end of JSON input at chatbot.js:57:22

I verified that the frontend code is sending a POST request to the correct endpoint ("/predict"). I also confirmed that CORS is correctly configured on the Flask server.

from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
from chat import get_response

app = Flask(__name__)
CORS(app)

@app.post("/predict")
def predict():
    text = request.get_json().get("message")
    print("Received message:", text)
    response = get_response(text)
    message = {"answer": response}
    return jsonify(message)


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

Under is my chatbot.js file with the post method

fetch("/predict", {
  method: "POST",
  body: JSON.stringify({ message: text1 }),
  mode: "cors",
  headers: {
    "Content-Type": "application/json",
  },
})
  .then((r) => r.json())
  .then((r) => {
    let msg2 = { name: "Sam", message: r.answer };
    this.messages.push(msg2);
    this.updateChatText(chatbox);
    textField.value = "";
  })
  .catch((error) => {
    console.error("Error:", error);
    this.updateChatText(chatbox);
    textField.value = "";
  });
1

There are 1 best solutions below

0
Hidayet Ozsoy On

as @pptx704 mentioned, you may forgot to specify the method.

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