Понимание того, как получить функцию облака с помощью CORS - PullRequest
0 голосов
/ 10 февраля 2020

Я развернул облачную функцию Python, показанную в документации Google .

def cors_enabled_function(request):
    # For more information about CORS and CORS preflight requests, see
    # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
    # for more information.

    # Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*'
    }

    return ('Hello World!', 200, headers)

Когда я получаю конечную точку из браузера следующим образом:

fetch('https://this-is-a-secret.cloudfunctions.net/cors-enabled-function',
{method: 'GET'}).then(response => console.log(response))

я получаю следующий Response объект:

Response {type: "cors", url: "https://this-is-a-secret.cloudfunctions.net/cors-enabled-function", redirected: false, status: 200, ok: true, …}
type: "cors"
url: "https://this-is-a-secret.cloudfunctions.net/cors-enabled-function"
redirected: false
status: 200
ok: true
statusText: ""
headers: Headers {}
body: (...)
bodyUsed: false
__proto__: Response

Если я это сделаю то же самое, но с помощью метода POST я получаю точно такой же результат. Если я изменю метод на PUT, он выдаст ошибку, которая ожидается, потому что я разрешаю только метод GET.

У меня следующий вопрос: Почему мне не показывают та же ошибка, когда я получаю с POST?

1 Ответ

0 голосов
/ 11 февраля 2020

Если вы установите:

if request.method == 'GET':

1.Рассматривая `curl -X POST или PUT url и проверяйте 'прочитанные журналы функций gcloud', вы увидите:

 Function execution took 9 ms, finished with status code: 200

Если вы проверите curl -v вы увидите, что заголовки:

 access-control-allow-origin: *

2. Запустив 'curl -X GET url' и проверив 'прочитанные журналы функций gcloud', увидите:

 Function execution took 13 ms, finished with status code: 204

Если вы проверите curl -v, вы увидите, что заголовки:

 < access-control-allow-headers: Content-Type
 < access-control-allow-methods: GET
 < access-control-allow-origin: *
 < access-control-max-age: 3600

Поэтому я не понимаю, что вы имеете в виду, когда получаете точно такой же результат при выполнении GET и POST.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...