首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django-cors-headers不适用于Expo-web

Django-cors-headers不适用于Expo-web
EN

Stack Overflow用户
提问于 2019-09-05 20:48:39
回答 1查看 611关注 0票数 0

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

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

代码语言:javascript
复制
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 allowed头文件。即使我使用django-cors-headers并允许所有设置,静态文件也无法加载,并显示错误消息:

代码语言:javascript
复制
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不能工作?还是我漏掉了什么?

EN

回答 1

Stack Overflow用户

发布于 2019-09-07 10:33:40

有很多问题。

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

当您登录并使用cookie时,您应该为axios设置withCredentials: true

接下来,静态文件不会通过Django中间件,因此您必须手动为静态文件设置CORS头。

代码语言:javascript
复制
#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上显示。原因是react-native-web不支持aspectRatio。您必须根据您自己的比例手动设置widthheight

代码语言:javascript
复制
<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,
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57805872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档