不允许使用 GET405 方法(JavaScript 和 Flask)

GET405 method not allowed (JavaScript and Flask)

我正在开始 Javascript 与 Flask 服务器交互的开发。当我发出请求(post 或获取)时,我总是出现 405 方法不允许错误。

这是我的 JavaScript 代码:

        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);
            })
        }
    }
        })

还有我的 python 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)

我看了很多论坛,但没有任何效果...

非常感谢。

Fetch 默认使用 GET 请求。

您的 Flask 应用仅在该端点上接受 POST。告诉 fetch 到 POST 到端点。

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

阅读更多关于 MDN