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.

Error are not reported using CORS middleware

See original GitHub issue

Checklist

  • The bug is reproducible against the latest release and/or master.
  • There are no similar issues or pull requests to fix it yet.

Describe the bug

When using CORS middleware, if calling endpoint lead to any unexpected error, the response sent would not hold proper headers leading to the classic TypeError: Origin XXX is not allowed by Access-Control-Allow-Origin. error message from browser.

To reproduce

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

api = FastAPI()
api.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'])


@api.get('/')
def index():
    return """
    <html>
        <body>
              <div id="container"></div>
             <script>
                fetch('/error').catch(function(reason) { document.getElementById('container').innerHTML = reason }); 
            </script>
        </body>
    </html>
    """


@api.get('/error')
def errorcase():
    raise ValueError

Expected behavior

This is misleading as we expect to received a proper HTTP 500 Internal Server Error response at least.

Actual behavior

The returned response does not hold proper CORS Header leading to wrong response in browser.

Environment

  • Python version: 3.7 (latest)
  • Starlette version: latest

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:3
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

8reactions
leandrorebelocommented, Mar 29, 2021

I have the same issue here. We are using the FastAPI (0.63.0) and Starlette (0.13.6).

So, I was debugging the request I saw that the CORSMiddleware doesn’t call the method send when the Exception is not an HTTPException (StarletteHTTPException).

In this way the CORSMiddleware works.

    def get_test() -> str:
        raise HTTPException(
            status_code=HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Error with HTTPException"
        )

In this way, the CORSMiddleware fails.

    def get_test() -> str:
        raise Exception
1reaction
jcwilsoncommented, Jul 21, 2021

After going through that exercise I think the more elegant option may be to adopt your workaround. More generally - allow developers to easily add middlewares “outside” of the ServerErrorMiddleware.

Read more comments on GitHub >

github_iconTop Results From Across the Web

CORS errors and how to solve them - Topcoder
Open a network tab in your console. ... In the response header look for the Access-Control-Allow-Origin header. If it does not exist then...
Read more >
How to fix those confusing CORS errors when calling your ...
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Read more >
I can't get the Cors middleware to work in my Node.js App
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Read more >
How to deal with CORS error in express Node.js Project
Step 1: Create a Node.js application and name it gfg-cors using the following command. · Step 2: Install the dependency modules using the ......
Read more >
Troubleshoot CORS errors from API Gateway - AWS
Resolution · The API isn't configured with an OPTIONS method that returns the required CORS headers. · Another method type (such as GET,...
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