0

我很难允许对 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 不能总是看到所有标题。有没有人遇到过这个?谢谢你。

4

1 回答 1

1

一个可能的场景——

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


我建议您使用 Falcon 或 Flask。如果仅在 gunicorn 或服务员下使用 Falcon,以下过程可能会有所帮助-

获取猎鹰

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传入请求中有,请确保您不要错过上面的allow_credentials_origins_list设置。whitelisted_originscors

或者

如果要允许凭据,则不应设置allow_all_originsTrue. 您必须在allow_credentials_origins_list.

于 2020-01-24T14:27:54.053 回答