question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] I can't enable CORS

See original GitHub issue

I set up a Dockerimage that uses fastapi version 0.45.0 and uvicorn. I need to enable CORS for different domains like id-localtest.mydomain.com, id-alpha.mydomain.com and id.mydomain.com. In my main.py file I wrote these lines of code

from fastapi import FastAPI, HTTPException

app = FastAPI()

origins = ['https://id-localtest.mydomain.com', 'https://id-alpha.mydomain.com', 'https://id.mydomain.com']

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["DELETE,GET,POST,PUT"],
    allow_headers=["*"])

@app.post("/{stage}/activation")
async def activation_post(stage: str, request: Request):
    # my custom code
    return 200

I’m always getting an HTTP status code 400 when a generic browser makes an OPTIONS request. If I try to use Postman to make an OPTIONS request, I get the HTTP status code 405 and the json received is:

{
    "detail": "Method Not Allowed"
}

What am I doing wrong? I’m following this tutorial https://fastapi.tiangolo.com/tutorial/cors/

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

11reactions
nsidnevcommented, Jan 7, 2020

starlette.middleware.cors.CORSMiddleware accepts a sequence of strings in allow_methods parameter. Try replacing your line with:

    allow_methods=["DELETE", "GET", "POST", "PUT"],

Also, your browser does not send a simple OPTIONS request, but a preflight-request. You can send it manually by specifying special headers for your request. Here is an example for your application using httpie:

$ http --verbose OPTIONS :8000/stage/activation Access-Control-Request-Method:POST Origin:https://id-localtest.mydomain.com

OPTIONS /stage/activation HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Connection: keep-alive
Content-Length: 0
Host: localhost:8000
Origin: https://id-localtest.mydomain.com
User-Agent: HTTPie/1.0.3



HTTP/1.1 200 OK
access-control-allow-credentials: true
access-control-allow-methods: DELETE, GET, POST, PUT
access-control-allow-origin: https://id-localtest.mydomain.com
access-control-max-age: 600
content-length: 2
content-type: text/plain; charset=utf-8
date: Tue, 07 Jan 2020 15:19:54 GMT
server: uvicorn
vary: Origin

OK
0reactions
hanzohancommented, Mar 12, 2021

please note that you can also add

  • main domain
  • sub domain
  • different port

in origins sections, for example:

origins = [
    "https://aaa.com", # main domain, targeting HTTPS port [433] by default because we don't specify the port.
    "https://abc.aaa.com", # subdomain, targeting HTTPS port [433] by default because we don't specify the port.
    "https://aaa.com:4000" # main domain, targeting 4000 port
]

you can also allow all standard methods by set allow_methods=["*"]

for example:

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
Read more comments on GitHub >

github_iconTop Results From Across the Web

3 Ways to Fix the CORS Error — and How the Access-Control ...
Fix one: install the Allow-Control-Allow-Origin plugin. The quickest fix you can make is to install the moesif CORS extension .
Read more >
Cant enable CORS on the server side NodeJS - Stack Overflow
You explicitly disallowed CORS on the client side by setting mode: 'same-origin' instead of the default mode: 'cors' . To quote the docs:....
Read more >
What Is a CORS Error and How to Fix It (3 Ways) - Bannerbear
Solution 1: Configure the Backend to Allow CORS · Solution 2: Use a Proxy Server · Solution 3: Bypass the Error Using a...
Read more >
Fixing Common Problems with CORS and JavaScript
Tutorial: This post walks through troubleshooting and fixing common problems associated with calling REST APIs from JavaScript.
Read more >
Troubleshoot CORS errors from API Gateway - Amazon AWS
To resolve a CORS error from an API Gateway REST API or HTTP API, ... Configure CORS on your API resource that's experiencing...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found