问题
I've searching a lot and although I found similar issues, it seems that I haven't found my answer yet and maybe you can help me.
I have the following API on my Web2Py framework and I am accessing it with a AngularJS front-end app and I am having CORS issues (I already tried * in the orign or my specific IP and port but no good results). Nevertheless, it does work with IE but not with Chrome or Mozilla.
@request.restful()
def api():
def GET():
key = main() #generate random XML and returns the key
response.headers['Content-Type'] = '*'
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Max-Age'] = 86400
response.headers['Access-Control-Allow-Headers'] = '*'
response.headers['Access-Control-Allow-Methods'] = '*'
response.headers['Access-Control-Allow-Credentials'] = 'true'
response.view = 'generic.xml'
value = cb.get(key).value #get value stored into couchbase
return value
return dict(GET=GET)
More details about the error from the front-end app:
XMLHttpRequest cannot load http://my_IP:8000/my_app/default/api/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://my_IP:8080' is therefore not allowed access. The response had HTTP status code 405.
From my front-end app I am sure I have the right function for calling the API.
Thanks!
回答1:
Your response headers need to go outside of the GET() function.
@request.restful()
def api():
response.view = 'generic.json'
response.headers["Access-Control-Allow-Origin"] = '*'
response.headers['Access-Control-Max-Age'] = 86400
response.headers['Access-Control-Allow-Headers'] = '*'
response.headers['Access-Control-Allow-Methods'] = '*'
response.headers['Access-Control-Allow-Credentials'] = 'true'
def GET(tablename, id):
if not tablename == 'person':
raise HTTP(400)
return dict(person = db.person(id))
def POST(tablename, **fields):
if not tablename == 'person':
raise HTTP(400)
return db.person.validate_and_insert(**fields)
return locals()
http://web2py.com/books/default/chapter/29/10/services?search=restful#Low-level-API-and-other-recipes
来源:https://stackoverflow.com/questions/34621368/cors-issue-with-api-running-on-web2py