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.

ブラウザーで (いずれかの PC で) URL に直接移動すると、問題なく読み込まれます。しかし、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: truehttpOptions.


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

参考までに、受信リクエストに がある場合は、上記のset toをwithCredentials: true見逃さないようにしてください。allow_credentials_origins_listwhitelisted_originscors

また

資格情報を許可する場合は、に設定allow_all_originsしないでくださいTrue。で正確なプロトコル + ドメイン + ポートを指定する必要がありますallow_credentials_origins_list

于 2020-01-24T14:27:54.053 に答える