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)
}
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.