无法使用axios将POST请求发送到Flask应用

时间:2019-08-12 06:46:25

标签: flask cors axios

我只是想使用axios向Flask发送json发布请求。但是我在服务器控制台中收到“ OPTIONS”信息,据了解这是预检请求。而且我发现,如果我在axios的标头中使用x-www-form-urlencoded而不是application / json,则浏览器不会执行预检请求,因此最终得到了POST请求。但是POST请求块(如您在下面的代码中看到的)仍然没有被击中。即使在服务器中设置了访问控制允许来源,我仍然遇到CORS问题。这可能是什么问题?

//FLASK SERVER
@bp.route("/", methods=["GET", "POST"])
def recipes():
    if request.method == "GET":
        # show all the recipes
        recipes = [
            {'name': 'BURGER', 'ingredients': ['this', 'that', 'blah']},
            {'name': 'CHICKEN'}
        ]
        return jsonify(recipes)
    elif request.method == "POST":
        # save a recipe
        print('SEE HEREEE'+ str(request.data))
        print(request.is_json)
        content = request.get_json()
        print(content)
        return jsonify(content), 201, {'Access-Control-Allow-Origin': '*', 'Access-Control-Request-Method': "*", 'Access-Control-Allow-Headers': "*"}



//FRONTEND
try{
      let response = await axios({
        method: "POST",
        url: "http://localhost:5000/recipes/",
        headers: {
          "Content-Type": "*"
        },
        data: {"hello": "HI"}
      });
      console.log("RESPONSE HERE", response)
    }catch(err){
      throw new Error("ERROR", err)
    }  

//浏览器控制台 Browser console

1 个答案:

答案 0 :(得分:1)

如果Python代码中有任何错误,则会在前端显示类似的错误。从您的屏幕截图中,我发现LoginForm中存在错误。我认为这就是前端无法按预期运行的原因。

要处理CORS错误,我使用了flask_cors Flask扩展名。有关该软件包的详细信息,请参见in this Pypi package repository

我简化了代码,以测试后端无错误时是否发生CORS错误。我可以使用来自Axios的POST请求添加新配方。

后端:

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

app = Flask(__name__)
CORS(app)

@app.route("/recipes", methods = ['GET', 'POST'])
def recipes():
    # recipes
    recipes = [
        {'name': 'BURGER', 'ingredients': ['this', 'that', 'blah']},
        {'name': 'HOTDOG', 'ingredients': ['Chicken', 'Bread']}
    ]

    if request.method == "GET":
        return jsonify(recipes)
    elif request.method == "POST":
        content = request.get_json()
        recipes.append(content)
        return jsonify(recipes)

前端:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>Frontend Application</title>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
  <div id="result">

  </div>
  <script type="text/javascript">
    axios.post('http://127.0.0.1:5000/recipes', {
      name: 'Sandwich',
      ingredients: ['Vegetables', 'Sliced cheese', 'Meat']
    })
    .then(function (response) {
      var result = document.getElementById("result");
      const data = response.data;
      for(var i=0; i<data.length; i++){
        const item = data[i];
        result.innerHTML+=item.name+": "+item.ingredients+"<br>";
      }
    })
    .catch(function (error) {
      console.log(error);
    });
  </script>
</body>
</html>

输出:

output