静态资产上的Django CORS [英] Django CORS on static asset

查看:63
本文介绍了静态资产上的Django CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Django作为后端,并且遇到了跨源问题,该问题已在设置中使用 corsheaders 程序包解决。到目前为止,由于以下原因,我所有的GET端点都能正常工作:

I'm using Django as a backend, and have run into cross origin issues which I had fixed using the corsheaders package in settings. So far, all my GET endpoints work, thanks to:

CORS_ORIGIN_ALLOW_ALL = True

但是,我现在正在尝试访问django后端的静态文件,其位置如下:

However, I'm now trying to access a static file on the django backend, located as such:

http://localhost:8000/static/image.jpg

但是,浏览器客户端会像以前一样收到熟悉的错误:

The browser client however gets the familiar error as before:

Access to XMLHttpRequest at ... from origin ... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

有什么想法吗?谢谢

推荐答案

我假设您正在使用内置的 staticfiles 应用,可在开发中提供您的静态文件。当将 runserver 管理命令与 staticfiles 一起使用时,它使用WSGI处理程序来提供绕过中间件的静态文件。 ( Django文档

I'm assuming you're using the built-in staticfiles app to serve your static files in development. When using the runserver managment command along with staticfiles, it uses a WSGI handler to serve static files that bypasses middleware. (Django docs)

您可以通过运行 python manage.py runserver --nostatic 禁用此功能。当您使用-nostatic 时,它将通过Django urlconf处理与所有其他URL相同的静态URL,因此请不要忘记在根urlconf中包含静态文件URL。像这样:(请参见静态文件开发视图

You can disable this by running python manage.py runserver --nostatic. When you use --nostatic it will handle static URLs the same as all other URLs, through your Django urlconf, so don't forget to include the staticfiles URLs in your root urlconf like so: (see Static file development view)

if settings.DEBUG:
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    urlpatterns += staticfiles_urlpatterns()

这篇关于静态资产上的Django CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆