'python service access to ajax call , CORS error
I'm getting lost with this problem, i have a service written in python that i need to access from a web page with an ajax call
the python code is as follows:
import flask
from flask import request, jsonify, make_response
from flask_cors import CORS, cross_origin
from datetime import datetime, timedelta
app = flask.Flask(__name__)
app.run(host='0.0.0.0', port=5000)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route('/api/v1/resources/device/all', methods=['GET'])
@cross_origin()
def api_all():
[...]
response = jsonify(result)
response.headers.add("Access-Control-Allow-Origin", "*")
return response,status_code
and the ajax call is:
$.ajax({
type: 'get',
crossDomain: true,
dataType: "json",
url: AddressWS + '/api/v1/resources/device/all?type=A',
success: function (result) {
//.,...
}
});
The error is ever
... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
the web application is under IIS . the question is : if I set 0.0.0.0 as address in python script, which address should I call in the web application ? i try to machine ipv4 address but don't run. how i fix the cors problem, i seem to have correctly included the flask libraries.
Thanks everyone for the kind replies
Solution 1:[1]
CORS is not configured properly in your code. Please find below the code with the correct CORS configuration.
import flask
from flask import request, jsonify, make_response
from flask_cors import CORS
from flask_restful import Api
from datetime import datetime, timedelta
app = flask.Flask(__name__)
api = Api(app)
CORS(app)
@app.route('/api/v1/resources/device/all', methods=['GET'])
def api_all():
[...]
response = jsonify(result)
status_code = 'some code'
return response,status_code
if __name__ == '__main__':
app.run()
Solution 2:[2]
Try this in my case it works ,
$.ajax({
type: 'get',
dataType: 'json',
url: AddressWS + '/api/v1/resources/device/all?type=A',
cors: true,
contentType: 'application/json;charset=UTF-8',
secure: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
success: function (result) {
//.,...
},
error: function (errorMessage) {
console.log('error');
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Vimlesh Bhatt |
Solution 2 |