首页 > 解决方案 > 调用烧瓶 API 时不允许使用 POST 方法。确切的错误:POST http://127.0.0.1:5000/405(不允许的方法)

问题描述

我正在创建一个成绩预测应用程序,其中我有一个 React 表单前端和一个 Flask API,我将数据发送到 api,并在使用随机森林分类器预测它后返回我一个成绩。我以前从未创建过烧瓶 api,也找不到答案。这是我的烧瓶 api 代码:

from flask import Flask, request, jsonify, make_response
import joblib
import numpy as np
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

classifier = joblib.load("random_forest_grade.joblib")

@app.route("/", methods = ['GET']) 
def home():
    return "Hello world"

@app.route("/grades", methods=['POST', "GET"])
def grades():
    if request.method == "POST":
        try:
            formData = request
            data = [val for val in formData.values()]
            prediction = classifier.predict(np.array(data).reshape(1, -1))
            types = {0:"A",1:"B",2:"C",3:"D",4:"F"}
            response = jsonify({
            "statusCode": 200,
            "status": "Prediction made",
            "result": types[prediction[0]]
            })
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response
        except Exception as error:
            return jsonify({
                "statusCode": 500,
                "status": "Could not make prediction",
                "error": str(error)
            })

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

这是我调用flask api的React函数

    submitForm = () =>{
    const {formData,step, isLoading, result} = this.state
    this.setState({isLoading:true, step: step+1})
    const newCurrent = Math.ceil(formData.current/5)-3
    
    this.setState({formData: {...formData, current: newCurrent}})
    axios.post('http://127.0.0.1:5000/', formData)
    .then(response => {
      this.setState({
        result: response.result,
        isLoading: false
      });
    }).catch(err =>{
        this.setState({
            result: "Does not work",
            isLoading: false
          });
    });
}

标签: javascriptreactjsapiflaskpost

解决方案


我认为您必须修复 URL,从http://127.0.0.1:5000/http://127.0.0.1:5000/grades


推荐阅读