Jaroslav KlimĨík Jaroslav KlimĨík - 1 year ago 150
Python Question

Javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource

I need to send data throught XmlHttpRequest from javascript to python server. Because I'm using localhost I need to use CORS. I'm using Flask framework and his 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) {

and python code:

@app.route('/signin', methods=['POST'])
def sign_in():
email = cgi.escape(request.values["email"])
password = cgi.escape(request.values["password"])

but when I execute it I will 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 I should 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 use pure javascript. Thank you

Answer Source

I got Javascript working with Flask by using this decorator, and adding "OPTIONS" to my list of acceptable methods. The decorator should be used beneath your route decorator, like this:

@app.route('/login', methods=['POST', 'OPTIONS'])
def login()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download