【问题标题】:POST method not allowed when calling flask API. exact error: POST http://127.0.0.1:5000/405 (METHOD NOT ALLOWED)调用烧瓶 API 时不允许使用 POST 方法。确切的错误:POST http://127.0.0.1:5000/405(不允许的方法)
【发布时间】:2021-09-09 07:38:09
【问题描述】:

我正在创建一个成绩预测应用程序,其中我有一个 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)

这是我调用烧瓶 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
          });
    });
}

【问题讨论】:

    标签: javascript reactjs api flask post


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-10-16
      • 2018-12-20
      • 2014-03-08
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      • 2016-02-15
      相关资源
      最近更新 更多