I have a Flask API set up on a linode server. Using Nginx and Gunicorn, I now forward connections from the public IP to a Flask API.py file.
Running on a server using simpleHTTPServer, I am attempting to make GET Requests to the Flask API using AJAX along with the route URI. Testing the URI and its argument returns the expected result when I type it into my web browser, but any attempted connections made by the simpleHTTPServer result in a CORS error
Access to XMLHttpRequest at '176.58.103.74/api/v1/proxy' from origin 'localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Any Ideas how to fix? Heres my Flask and AJAX Code.
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
@app.route('/api/v1/proxy', methods=['GET'])
def api_id():
headers = {'User-Agent': 'MonkeyPuzzle_Web_v1'}
address = request.args.get('address')
new_address = address.replace('www.', 'https://', 1)
resp = requests.get(new_address, headers=headers)
return jsonify(result=resp.text)
$.ajax({
type: 'GET',
url: '176.58.103.74/api/v1/proxy', //this will work if the napier server can be used
data:{'address' : title},
success: function(data) {
$("#webIframe_" + tab_id).attr('srcdoc', data.result);
console.log(data);
}
});
Girish Patil
Full-stack engineer
Because your frontend and backend runs on different origins/ips/domain. Cross origin requests are not allowed by default. You can overcome this by either.
Ref. to isomorphic apps with python. I havent read this article though. https://medium.com/@amol/going-isomorphic-with-python-and-react-f4664183f0c4 Ref. to cors developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Set
Access-Control-Allow-Originheader to*.Warning : This will allow any origin to make requests to your backend. You can specify particular origins to restrict access.might
I hope it helps you out some way.