Django CORS-任何端口的本地主机

发布于 2025-02-07 04:06:11 字数 434 浏览 1 评论 0原文

我遇到了我的Django应用程序的CORS问题。我已经正确配置了它,并且将问题范围缩小到我的URL列表 - 设置cors_origin_allow_all_all = true修复了它。

这是我的当前列表:

CORS_ALLOWED_ORIGINS = [
    "http://localhost",
    ...
]

我的前端是一个颤动的应用程序,问题在于,在开发中,在任何随机端口,例如localhost:12345 ,所以我无法将其硬代码将其硬编码到CORS中列表。

如何将localhost添加到列表中的任何任意端口?我似乎找不到关于它的文档,唯一的选择似乎只是允许我宁愿不做的一切。

I'm running into a CORS issue with my Django app. I've got it configured properly and I've narrowed the issue down to my list of URLs - settings CORS_ORIGIN_ALLOW_ALL = True fixes it.

This is my current list:

CORS_ALLOWED_ORIGINS = [
    "http://localhost",
    ...
]

My front end is a Flutter app, the problem is that in development Flutter runs on any random port e.g., localhost:12345, so I can't hard code this into the CORS list.

How can I add localhost with any arbitrary port to the list? I can't seem to find docs on it, the only alternative seems to be to just allow everything which I'd prefer not to do.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半寸时光 2025-02-14 04:06:11

我实际上意识到如何在发布后立即解决此问题。

django-cors-headers 软件包也支持regex匹配。我最终使用以下内容:

CORS_ALLOWED_ORIGIN_REGEXES = [
    # match localhost with any port
    r"^http:\/\/localhost:*([0-9]+)?$",
    r"^https:\/\/localhost:*([0-9]+)?$",
]

这将匹配https:// localhost:< port> and http:// localhost:< port>

I actually realized how to solve this right after posting.

The django-cors-headers package supports regex matching as well. I ended up using the following:

CORS_ALLOWED_ORIGIN_REGEXES = [
    # match localhost with any port
    r"^http:\/\/localhost:*([0-9]+)?
quot;,
    r"^https:\/\/localhost:*([0-9]+)?
quot;,
]

This will match https://localhost:<PORT> and http://localhost:<PORT>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文