django React全堆栈:无法从Rest API提取项目详细信息

mec1mxoz  于 2022-12-14  发布在  Go
关注(0)|答案(3)|浏览(87)

我正在开发一个全栈的django和react应用程序,目前它只是从API中获取数据,我也可以获取第一个项目的详细信息页面,但不能为第二个项目做同样的事情。它显示以下错误,当我试图从django获取第二个项目(奇怪,但它对id = 1的第一项工作得很好,而不是对id = 2或3)。

另外,我把我的整个代码都放到了bitbucket上。您可以在这里调试前端和后端https://bitbucket.org/Yash-Marmat/react-django-blog/src/master/
先谢谢你了。

ruarlubt

ruarlubt1#

你需要使用proxy密钥在内部前端package.json文件中,如下所示

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://127.0.0.1:8000",

并重新启动React应用程序。

gv8xihay

gv8xihay2#

您的URL看起来很奇怪。请尝试更改URL:

urlpatterns = [
    path('', ArticleListView.as_view()),
    path('detail/<int:pk>/', ArticleDetailView.as_view()),
]

并在前端使用更改的URL访问。我可以推荐一个good tutorial for Django+React CRUD

8yparm6h

8yparm6h3#

您需要在您的django API中启用cors或跨源资源共享。
你可以通过安装这个叫做django-cors-headers的软件包来实现
Django cors headers github page

pip install django-cors-headers

然后将其添加到已安装的应用程序:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

您还需要添加一个中间件类来侦听响应:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',  
    ...
)

CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
    'http://localhost:3030',
]

更多详情:https://github.com/ottoyiu/django-cors-headers/#configuration
阅读官方文档可以解决几乎所有问题

相关问题