0

I'm simply trying to send a json post request using axios to Flask. But I get 'OPTIONS' in the server console which I understood is the preflight request. And I found if I use x-www-form-urlencoded instead of application/json in the headers of axios, the browser doesn't do a preflight request, so I was getting a POST request finally. But the block of POST request (as you can see in the code below) still doesn't get hit. I keep getting a CORS issue even though I've set the Access control allow origins in the server. What could be the problem here?

//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 Browser console

Bikal Nepal
  • 477
  • 1
  • 10
  • 26

1 Answers1

1

If there is any error in Python code it shows similar error in front end side. From your screenshot, I see that there is an error in LoginForm. I think that is why the front end is not working as expected.

To handle CORS error, I use flask_cors Flask extension. Details of the package can be found in this Pypi package repository.

I have simplified the code to test if the CORS error occurs when there is no error in back end. I can add a new recipe using POST request from Axios.

Backend:

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)

Frontend:

<!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:

output

arshovon
  • 13,270
  • 9
  • 51
  • 69
  • 1
    Thank you! I had actually already solved it using the flask-cors package just like you did and answered my question by myself 5 hrs ago, but someone deleted it :/ I'm not sure why, may be because I provided a link to the post on a website that solved my issue. Anyways, Is there anyway to solve this issue without using an external package? I'm guessing adding some parameters in the axios function in frontend should be able to do that?? but I'm not sure what. – Bikal Nepal Aug 12 '19 at 13:58
  • 2
    Glad to hear that you solved it. CORS can not be handled from frontend. Here is an article relating to this statement: https://medium.com/@jeanpan/what-is-cors-cross-origin-resource-sharing-9f0c463621c6 – arshovon Aug 12 '19 at 14:16