Search code examples
javascriptpython-3.xflaskhttp-status-code-405

GET405 method not allowed (JavaScript and Flask)


I'm starting a Javascript development that interacts with a Flask server. When I make a request (post or get) I always have a 405 method not allowed error.

Here is my JavaScript code:

        fetch('http://127.0.0.1:5053/api/prediction_lime').then(function (response) {
        const contentType = response.headers.get("content-type");
        if (contentType && contentType.indexOf("application/json") !== -1) {
            if (response.ok) {
                response.json().then(function (json) {
                app.showOneResult(0, json);
            })
        }
    }
        })

And my python code for Flask :

import flask
from flask import Flask, render_template, jsonify, request,send_file
from flask_cors import CORS, cross_origin
import numpy as np
import json
import os
#import pandas

print(flask.__version__)

app = Flask(__name__,template_folder='.')
CORS(app, origins="http://127.0.0.1:8080", allow_headers=[
    "Content-Type", "Authorization", "Access-Control-Allow-Credentials"],
    supports_credentials=True)



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

@app.route('/api/predictions',methods=['POST'])
def predictions():
    # Cette fonction
    params = request.get_json(force=True)
    print(params)
    with open('predictions.json', encoding='utf8') as f:
        data = json.load(f)
        return jsonify(data)

@app.route('/api/prediction_lime',methods=['POST'])
def prediction():
    # Cette fonction
    params = request.get_json(force=True)
    print(params)
    with open('prediction_lime.json', encoding='utf8') as f:
        data = json.load(f)
        return jsonify(data)

I have read many forums but nothing works...

Thank you very much.


Solution

  • Fetch uses a GET request by default.

    Your flask app only accepts POST on that endpoint. Tell fetch to POST to the endpoint instead.

    fetch('http://127.0.0.1:5053/api/prediction_lime', {
            method: "POST"
            })
    

    Read more on MDN