推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
Richard14
V2EX  ›  Python

FastAPI 跨域工作不正常, CORS 可以支持二级域名吗?

  •  
  •   Richard14 · Apr 21, 2022 · 3216 views
    This topic created in 1621 days ago, the information mentioned may be changed or developed.

    在 github pages 的网页里调用自己的 fastapi 后端,需要单独设置一下 CORS 。目前后端使用下面的代码是能正常工作的

    from fastapi.middleware.cors import CORSMiddleware
    
    app = FastAPI()
    
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*", ],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    

    但是将*号改成自己的网址的话却会显示请求被 cors 拒绝,搞不太清楚哪步出了问题

        allow_origins=["https://my.github.io", ] # 改成这样以后就访问不了了
    

    是因为 cors 只支持 https://*.github.io 这种写法吗?还是后端反向代理的原因,请求经过 nginx 反向代理到 fastapi 以后 origin 变了?

    3 replies  •  2022-04-21 14:39:22 +08:00
    lisongeee
        1
    lisongeee  
       Apr 21, 2022
    被拒绝是浏览器拒绝还是服务器拒绝?,完整的网络请求日志是什么?
    LeeReamond
        2
    LeeReamond  
       Apr 21, 2022
    感觉不应该有问题,cors 没有不支持二级域名的说法,nginx 反向代理也不会替换 origin
    xuanbg
        3
    xuanbg  
       Apr 21, 2022
    allow_origins 星号现在不行了,也不能写多个域名。。。你要从请求头获取 origin 的值然后赋值给 allow_origins 才行。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   860 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 21:36 · PVG 05:36 · LAX 14:36 · JFK 17:36
    ♥ Do have faith in what you're doing.