4
votes

I try to make a POST to a flask server using axios:

var config = { headers: {  
                      'Content-Type': 'application/json',
                      'Access-Control-Allow-Origin': '*'}
             }
 axios.post("http://127.0.0.1:5000/test", 
             { label : "Test" , text : "Test"}  , config
          )
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });

Now the part of Flask

...
data = request.get_json(silent=True)
item = {'label': data.get('label'), 'text': data.get('text')}
print item
...

However, I ll end up with the following error:

XMLHttpRequest cannot load http://127.0.0.1:5000/test. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Why? I LL set the header as suggested.

Here the solution

from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app, resources={r"/YOURAPP/*": {"origins": "*"}})
2

2 Answers

3
votes

You need to add CORS support to your Flask app. See a related threat here: Flask-CORS not working for POST, but working for GET. A popular CORS extension for Flask can be found here: https://flask-cors.readthedocs.io/en/latest/.

0
votes

If anyone else is stuck, be sure to check your before and after request methods. My problem was this:

@app.before_request
def oauth_verify(*args, **kwargs):
    """Ensure the oauth authorization header is set"""
    if not _is_oauth_valid():
        return some_custome_error_response("you need oauth!")

So then this would raise an exception on any request, including an OPTIONS method. Of course, the fix is easy:

@app.before_request
def oauth_verify(*args, **kwargs):
    """Ensure the oauth authorization header is set"""
    if request.method in ['OPTIONS', ]:
        return
    if not _is_oauth_valid():
        return some_custome_error_response("you need oauth!")