【问题标题】:Django-cors-headers does not work with Expo-webDjango-cors-headers 不适用于 Expo-web
【发布时间】:2020-01-08 09:05:55
【问题描述】:

我刚刚在http://192.168.0.6:19006 运行了一个Expo-web 开发服务器,出现了很多问题。

当我没有安装 django-cors-headers 时,只加载了主页,其他任何请求都失败了。我很快意识到我必须安装 django-cors-headers。所以我做了。但是后来我的网络应用程序无法保持登录状态。登录过程本身在服务器端是成功的。客户端收到一条消息,告知登录成功。但是当它转换到下一页时,它会自动退回到主页(正如我设置的那样),因为应用程序无法保持登录状态。我假设 cookie 凭据有问题。但我设置的凭据设置如下:

CORS_ORIGIN_WHITELIST = [
    'http://192.168.0.6:19006',
]
CORS_ALLOW_CREDENTIALS = True
SESSION_COOKIE_SAMESITE = None

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
...
]
INSTALLED_APPS = [
    ...
    'corsheaders',
]

另一个问题是静态文件不提供 CORS 允许的标头。即使我使用 django-cors-headers 并允许所有设置,静态文件也无法加载并显示错误消息:

Access to XMLHttpRequest at 'http://192.168.0.6:8000/static/app%20Terms%20of%20Service.json' from origin 'http://192.168.0.6:19006' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

为什么CORS_ALLOW_CREDENTIALS = True 不起作用?还是我缺少什么?

【问题讨论】:

  • 在您的设置中将 CORS_ORIGIN_ALLOW_ALL 设置为 True 是否有效?
  • @JulienKieffer 不,我已经尝试过那个,不幸的是它对我不起作用。我猜问题出在客户端,而不是 Django-cors-headers,因为我使用的是 Apollo websocket。
  • 我可以看到标头设置为 Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: 192.168.0.6:19006 和 Set-Cookie:... 所以登录成功并且 cookie寄了,送了。但它不适用于 Apollo websocket。

标签: django cors expo django-cors-headers react-native-web


【解决方案1】:

有很多问题。

首先,对于客户端来说,问题出在 axios 上。

你应该在登录和使用cookie时为axios设置withCredentials: true。

接下来,静态文件不经过 Django 中间件,所以你必须手动设置静态文件的 CORS 头。

#vevn\Lib\site-packages\django\views\statics.py

content_type, encoding = mimetypes.guess_type(str(fullpath))
content_type = content_type or 'application/octet-stream'
response = FileResponse(fullpath.open('rb'), content_type=content_type)
response["Last-Modified"] = http_date(statobj.st_mtime)

# cors middleware hook
from corsheaders.middleware import CorsMiddleware
corsMiddlewareInstance = CorsMiddleware()
corsMiddlewareInstance.process_response(request, response)

if encoding:
    response["Content-Encoding"] = encoding
return response

最后,我的 <Image> 组件没有显示在 react-native-web 上。原因是 aspectRatio 在 react-native-web 上不受支持。 width和height要按照自己的比例手动设置。

<View onLayout={event => this.setState({
                                width: event.nativeEvent.layout.width
                            })}
    >
<Image source={{ uri: this.props.image.uri }}
                style={{
                        width: this.state.width,
                        height: this.state.width ? this.state.width * this.props.image.height / this.props.image.width : null,

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 2015-03-18
    • 2018-04-24
    • 2016-06-08
    • 2016-11-16
    • 2018-06-23
    • 2017-09-24
    • 2015-11-18
    • 2015-02-21
    相关资源
    最近更新 更多