redux 为什么我从Django Rest Framework得到了301和CORS响应,而请求在Postman中运行良好?

yxyvkwin  于 2023-02-23  发布在  Go
关注(0)|答案(1)|浏览(129)

我尝试从React & Redux应用向Django应用发出API GET请求,但收到一个关于CORS的错误,响应为301。
下面是React & Redux代码:

const fetchClasses = createAsyncThunk(
  GET_CLASSES,
  async (id) => {
    const CLASSES_API = `http://127.0.0.1:8000/learning/classes?schoolPk=${id}`;
    const response = await fetch(CLASSES_API);
    const data = await response.json();
    return data;
  },
);

当我使用相同的代码来获取所有学校时,它可以工作。但是当我添加 id 参数来获取某个学校的所有班级时,我就得到了错误。下面是Django中的 views.py 代码。

# Create your views here.
class SchoolViewSet(viewsets.ModelViewSet):
   queryset = School.objects.all()
   serializer_class = SchoolSerializer

class ClassViewSet(viewsets.ModelViewSet):
serializer_class = ClassSerializer

def get_queryset(self):
    return Class.objects.filter(school=self.request.query_params['schoolPk'])

我试过在Django settings.py 文件中设置CORS。

ALLOWED_HOSTS = ['http://localhost:3000/', '127.0.0.1',]

CORS_ALLOWED_ORIGINS = ['http://localhost:3000',]

CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000',
)

CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_METHODS = [
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
]

CORS_ALLOW_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
]

CORS_EXPOSE_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
]

CORS_ALLOW_CREDENTIALS = True

我想我可能在React中遗漏了一些东西,因为每个请求在Postman

中都能完美地工作
我能错过什么吗?

8tntrjer

8tntrjer1#

CORS是用来保护客户端免受cookie窃取和 Postman 不是客户端。这就是为什么你不会得到错误的 Postman 。
在www.example.com中settings.py

INSTALLED_APPS = [
    //..
    'corsheaders',
    'rest_framework',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    
]

ALLOWED_HOSTS = ["127.0.0.1","localhost"]

如果这些都不能修复它,请在package.json中添加代理

"proxy": "http://127.0.0.1:8000",

相关问题