flask_cors and pythonanywhere

86 Views Asked by At

I want to host a python script (as server side), I hosted in pythonanywhere. I found error : access to XMLHttpRequest at 'https://sifo13.pythonanywhere.com/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. But the request status 200.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/',methods=['GET','POST'])
def getdata():
    text = str(request.args.get("excel_file_name"))
    return text


I find that to ignore this error you should use flask_cors (I installed in pythonanywhere). I noted that when I write from flask_cors import CORS the status of the request returned 500, and the page display Something went wrong: -(Something went wrong while trying to load this website; Please try again later. (The same code as below worked succeed in localhost server)

from flask import Flask,request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/',methods=['GET','POST'])
def getdata():
    text = str(request.args.get("excel_file_name"))
    return text

if __name__ == '__main__':
    app.run(debug=True)
    

this is the js code (but the error is showing also when I use method[get] manually)

document.getElementById("btn-submit").addEventListener("click",function(){
    var fd = new FormData();
    fd.append("excelfiles",document.getElementById("input_file").files[0]);
    sendexcel("fd")

});

function sendexcel(objet){
    var xml = new XMLHttpRequest();
    xml.open("POST","https://sifo13.pythonanywhere.com/",true);
    xml.onreadystatechange = function(){
        if(this.readyState = 4 && this.status ==200){
            var reponce = this.responseText;
            alert(reponce)
        }
    }
    xml.send("excel_file_name="+objet)
}
1

There are 1 best solutions below

0
Detlef On

If you want to send a form from the frontend of your site to the backend, you don't need Flask-CORS because the request comes from the same origin.

I'm assuming you want to send a file to the server via AJAX. The following example shows you how you can implement this project on pythonanywhere without much effort. I use the Fetch API for this. For more information about server-side code, I recommend this article.

from flask import (
    Flask, 
    render_template, 
    request
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.post('/data')
def getdata():
    file = request.files.get('file')
    return 'Got a file.' if file else 'Got no file.'
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Index</title>
</head>
<body>
    
    <form name="my-form">
        <input type="file" name="file" />
        <input type="submit" />
    </form>

    <script type="text/javascript">
        (function() {

            const form = document.querySelector('form[name="my-form"]');
            form.addEventListener('submit', function(evt) {
                evt.preventDefault();
                fetch('/data', { method: 'post', body: new FormData(this) })
                    .then(resp => resp.ok && resp.text())
                    .then(console.log);
            });

        })();
    </script>
</body>
</html>