Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios, POST request to Flask

Tags:

flask

axios

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": "*"}})
like image 308
Henrik Avatar asked Jul 28 '17 12:07

Henrik


1 Answers

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/.

like image 108
jacekbj Avatar answered Nov 07 '22 03:11

jacekbj