Python Falcon 和 Axios:无法允许 CORS



我在允许向 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 上(,它加载没有问题。但是当使用公理时,它会中断。

我尝试了以下策略:

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(在本地使用猎鹰:

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()

没有任何效果。当我在浏览器中检查响应时,我可以看到"访问控制-允许-origin":"*"我在某处读到,axios 并不总是能看到所有的标头。以前有人遇到过这种情况吗?谢谢。

一种可能的情况-

使用浏览器时,如果服务器需要,它会在您的请求中附加withCredentials: true。但是当涉及到 Angular 或 React 时,您必须在httpOptions中明确提供withCredentials: true


我建议你使用Falcon或Flask。 如果只是在枪角兽或女服务员下使用猎鹰,以下程序可能会有所帮助-

获取猎鹰

from falcon_cors import CORS

有一些列入白名单的方法

# Methods supported by falcon 2.0.0
# 'CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE'
whitelisted_methods = [
"GET",
"PUT",
"POST",
"PATCH",
"OPTIONS" # this is required for preflight request
]

在预检请求中了解更多信息。

搜索类如下

class Search:
def on_get(self, req, resp):
response_obj = {
"status": "success"
}
resp.media = response_obj

有一些白名单来源

whitelisted_origins = [
"http://localhost:4200",
"https://<your-site>.com"
]

在中间件中添加 cors

cors = CORS(
# allow_all_origins=False,
allow_origins_list=whitelisted_origins,
# allow_origins_regex=None,
# allow_credentials_all_origins=True,
# allow_credentials_origins_list=whitelisted_origins,
# allow_credentials_origins_regex=None,
allow_all_headers=True,
# allow_headers_list=[],
# allow_headers_regex=None,
# expose_headers_list=[],
# allow_all_methods=True,
allow_methods_list=whitelisted_methods
)
api = falcon.API(middleware=[
cors.middleware,
# AuthMiddleware()
# MultipartMiddleware(),
])

现在,您可以向班级添加路线。

from src.search import SearchResource
api.add_route('/search', SearchResource())

供您参考,如果传入请求中有withCredentials: true,请确保不会错过上述cors中设置为whitelisted_originsallow_credentials_origins_list

如果要允许凭据,则不应将allow_all_origins设置为True。您必须在allow_credentials_origins_list中指定确切的协议 + 域 + 端口。

相关内容

  • 没有找到相关文章

最新更新