M
M
MikUrrey2021-06-09 18:50:36
Nginx
MikUrrey, 2021-06-09 18:50:36

Access-Control-Allow-Origin, why doesn't the browser understand it?

Script code:

<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Expose-Headers: *");
header("Content-type: application/json");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

Request:
POST http://127.0.0.1/?/auth/login
{password: "123456", phone: "79999999999"}

Result:
Access to XMLHttpRequest at 'http://127.0.0.1/?/auth/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


If you run it in API Tester, the headers come:
access-control-allow-headers: *
access-control-allow-methods: *
access-control-allow-origin: *
access-control-expose-headers: *
connection: keep-alive
content-type: application/json
date: Wed, 09 Jun 2021 15:29:11 GMT
server: nginx/1.19.10
transfer-encoding: chunked


What the hell is this?

UPD: Found that nginx can't process OPTIONS requests (405). How to properly resolve them? So far none of the tricks I've googled have worked. I need to send such a request to the same path that would work for a normal GET or POST.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MikUrrey, 2021-06-09
@MikUrrey

The problem was solved by adding a rule to default.conf in location

if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Headers' '*';
            add_header 'Access-Control-Allow-Methods' '*';
            add_header 'Access-Control-Expose-Headers' '*';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }

I would like to control the headers sent by the script, but this will also work for now.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question