V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2022-04-21 10:27:45 +08:00 · 2388 次点击
    这是一个创建于 774 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在 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 条回复    2022-04-21 14:39:22 +08:00
    lisongeee
        1
    lisongeee  
       2022-04-21 10:31:13 +08:00
    被拒绝是浏览器拒绝还是服务器拒绝?,完整的网络请求日志是什么?
    LeeReamond
        2
    LeeReamond  
       2022-04-21 11:24:50 +08:00
    感觉不应该有问题,cors 没有不支持二级域名的说法,nginx 反向代理也不会替换 origin
    xuanbg
        3
    xuanbg  
       2022-04-21 14:39:22 +08:00
    allow_origins 星号现在不行了,也不能写多个域名。。。你要从请求头获取 origin 的值然后赋值给 allow_origins 才行。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2604 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:30 · PVG 23:30 · LAX 08:30 · JFK 11:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.