我很难允许对 Flask 服务器的 CORS 请求。客户端是使用 axios 的 React。客户端的错误是:
Access to XMLHttpRequest at <url> has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
如果我直接在浏览器中导航到 url(在任一 PC 上),它加载没有问题。但是当使用 axios 时它会中断。
我尝试了以下策略:
1)直接附加标题:
from wsgiref.simple_server import make_server
import falcon
import transform
import json
import engine
index = transform.reindex()
app = falcon.API()
class Search:
def on_get(self, request, response):
query = request.params['searchText']
result = engine.search(query, index)
response.append_header('access-control-allow-origin', '*')
response.status = falcon.HTTP_200
response.body = json.dumps(result)
search = Search()
app.add_route('/search', search)
if __name__ == '__main__':
with make_server('', 8003, app) as httpd:
print('Serving on port 8003...')
httpd.serve_forever()
2)通过中间件全局使用falcon_cors:
from wsgiref.simple_server import make_server
import falcon
from falcon_cors import CORS
from flask import jsonify
import transform
import json
import engine
cors = CORS(allow_origins_list=[
'<client ip>'
])
index = transform.reindex()
app = falcon.API(middleware=[cors.middleware])
class Search:
def on_get(self, request, response):
query = request.params['searchText']
result = engine.search(query, index)
response.status = falcon.HTTP_200
response.body = json.dumps(result)
search = Search()
app.add_route('/search', search)
if __name__ == '__main__':
with make_server('', 8003, app) as httpd:
print('Serving on port 8003...')
httpd.serve_forever()
1) 在本地使用 falcon-cors:
from wsgiref.simple_server import make_server
import falcon
from falcon_cors import CORS
from flask import jsonify
import transform
import json
import engine
cors = CORS(allow_origins_list=['*'])
index = transform.reindex()
app = falcon.API(middleware=[cors.middleware])
public_cors = CORS(allow_all_origins=True)
class Search:
cors = public_cors
def on_get(self, request, response):
query = request.params['searchText']
response.status = falcon.HTTP_200
response.body = json.dumps(result)
search = Search()
app.add_route('/search', search)
if __name__ == '__main__':
with make_server('', 8003, app) as httpd:
print('Serving on port 8003...')
httpd.serve_forever()
没有任何工作。当我在浏览器中检查响应时,我可以看到 'access-control-allow-origin': '*' 我在某处读到 axios 不能总是看到所有标题。有没有人遇到过这个?谢谢你。