skip to Main Content

When accesing http://localhost:8088/api/ from https://my.example.com, I have this CORS error.

Access to XMLHttpRequest at 'http://localhost:8088/api/' from origin 'https://my.example.com' 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.

OK, It is popular error for CORS, so I checked the server setting.

curl -X POST -F file=@test_material/0_for_django_testcase.png  -F metadata='{"test":"test"}' -i localhost:8088/api/ -H "Origin: https://my.example.com

It return this header,but It looks like https://my.example.com is allowed…?

HTTP/1.1 201 Created
date: Mon, 10 Jul 2023 12:53:50 GMT
server: uvicorn
content-length: 510
content-type: application/json
access-control-allow-credentials: true
access-control-expose-headers: Content-Disposition
access-control-allow-origin: https://my.example.com
vary: Origin

If so, Why this error happens?

I tested on both chrome, and firefox

Any help appreciated.

Next Trial

THanks to @jub0bs comment

I tried to check with

curl -X OPTIONS -F file=@test_material/0_for_django_testcase.png  -F metadata='{"test":"test"}' -i localhost:8088/api/ -H "Access-Control-Request-Method: POST" -H "Origin: https://my.example.com" 

It returns,

date: Mon, 10 Jul 2023 14:40:27 GMT
server: uvicorn
vary: Origin
access-control-allow-methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
access-control-max-age: 600
access-control-allow-credentials: true
access-control-allow-origin: https://my.example.com
content-length: 2
content-type: text/plain; charset=utf-8

It looks like accepting OPTIONS too…

FastAPI Server setting is like this

def add_cors_middleware(app: FastAPI):
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[
            "http://localhost:8021",
            "https://https://my.example.com",
        ],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["Content-Disposition"],
    )

2

Answers


  1. Chosen as BEST ANSWER

    I use secret mode of browser.

    It works......

    Maybe there is some cache?

    Thank you for helping the problem.

    Sorry for bothring you.


  2. replace this header’s value access-control-allow-origin: https://my.example.com
    from django server and add localhost:your_server_port_where_server_is_running instead of your website link

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search