I need to send data through XmlHttpRequest
from JavaScript to Python server. Because I'm using localhost, I need to use CORS. I'm using the Flask framework and its module flask_cors
.
As JavaScript I have this:
var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("POST", "http://localhost:5000/signin", true); var params = "email=" + email + "&password=" + password; xmlhttp.onreadystatechange = function() {//Call a function when the state changes. if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { alert(xmlhttp.responseText); } } xmlhttp.send(params);
and Python code:
@app.route('/signin', methods=['POST']) @cross_origin() def sign_in(): email = cgi.escape(request.values["email"]) password = cgi.escape(request.values["password"])
But when I execute it I get this message:
XMLHttpRequest cannot load localhost:5000/signin. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
How should I fix it? I know that I need to use some "Access-Control-Allow-Origin" header but I don't know how to implement it in this code. By the way I need to use pure JavaScript.
< access-control-allow-origin: * You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it! Thanks this helps to avoid all the hassle and test the code from localhost.
The error you get is due to the CORS standard, which sets some restrictions on how JavaScript can perform ajax requests. The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server.
I have used the flask-cors extension.
Install using pip install flask-cors
Then it's simply
from flask_cors import CORS app = Flask(__name__) CORS(app)
This will allow all domains
Old question, but for future googlers with this problem, I solved it (and a few other downstream issues having to do with CORS) for my flask-restful app by adding the following to my app.py file:
app = Flask(__name__) api = Api(app) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') return response if __name__ == '__main__': app.run()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With