【发布时间】:2021-04-26 21:37:08
【问题描述】:
我正在尝试同时集成 React 前端和 Django & DRF 后端。
我正在使用rest-hooks 来获取数据。 只有在资源中定义 urlRoot = 'api/somemodel' 时才会出现 CORS 错误。
但是每当我定义urlRoot = 'api/somemodel.json'(将.json 添加到资源urlRoot)时,我都会从API 中获取数据。
CategoryResource.ts
import { Resource } from '@rest-hooks/rest';
import { API_URL } from '../utils/server';
export default class CategoryResource extends Resource {
readonly id: number | undefined = undefined;
readonly name: string = '';
readonly description: string = '';
pk() {
return this.id?.toString();
}
static urlRoot = API_URL + 'categories.json';
}
以上代码仅适用于useResource(CategoryResource.list(), {}),但是,每当我使用useResource(CategoryResource.detail(), { id }) 获取一个类别时,由于URL 格式:http://localhost:8000/api/categories.json/1,它会返回一些网络错误。但应该是categories/1.json。
所以,我想,如果我能够在向http://localhost:8000/api/categories 发送请求时使用 Postman 以 JSON 格式获取所有类别,我应该使用它,但后来我收到了 CORS 错误。
CORS 配置
我的 Django 配置允许来自settings.py:CORS_ALLOW_ALL_ORIGINS = True 的所有来源。同样,它确实适用于第一种方法。但无论如何,这是我在 Python 中的配置文件:
INSTALLED_APPS = [
...
'rest_framework',
...
'django_filters',
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
# CORS // I have tried switching all of these
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
# CORS_ALLOWED_ORIGINS = [
# 'http://localhost:3000',
# ]
【问题讨论】:
-
首先你不应该在你的请求地址中使用
.json。您能否也解释一下您问题的最后一部分?当您在本地计算机上执行 CORS_ALLOW_ALL_ORIGINS 时,它只能工作,而 url 中没有.json? -
您是否正确配置了 cors?像 cors 中间件等。你能用你的 django 应用程序中的 CORS 相关设置更新你的问题吗?
-
我认为没有必要,因为我已经可以获取数据了。
-
@SadanA。但无论如何,我将它添加到问题中。
-
你在settings.py中添加了这个吗
ALLOWED_HOSTS = ['*']
标签: reactjs django typescript rest django-rest-framework