React,Django,Django REST和Axios存在大量问题 [英] A large number of problems with React, Django, Django REST and Axios
问题描述
这篇文章是以下系列的第一部分-
-
它应该看起来像这样-
(注意:通过在基本(应用)文件夹中修改urls.py,解决了产品展示的问题-
django.urls导入路径中的从 .导入视图urlpatterns = [path('',views.getRoutes,name ="routes"),path('products/',views.getProducts,name ="products"),path('products/< str:pk>/',views.getProduct,name ="product"),]
已更改为
django.conf.urls中的导入URL从 .导入视图urlpatterns = [url('products/',views.getProducts,name ="products"),url('products/< str:pk>/',views.getProduct,name ="product"),url('routes/',views.getRoutes,name ="routes"),]
)
当我查看控制台时,遇到很多错误,例如-(并非所有这些错误这是有害的,因为例如,与甚至在所有其他错误均未显示并且一切运行正常之前,就存在与crashOnSellect相关的问题
127.0.0.1:8000/api/products/:1无法加载资源:net :: ERR_CONNECTION_REFUSED
以下是有关控制台中第三个错误的更多详细信息-
(注意:解决以下(与路径相关和与静止有关的)错误后,该错误已消失)
另一个问题是,VSCode给我这两个错误-
模块'django.urls'中没有名称'path'
和模块'django.urls中没有名称'include'
(这些错误与两个urls.py文件有关)(注意:这些错误是通过将
path
更改为url
(在urls.py文件中)并从django.urls导入url更改为来解决的,包括
到django.conf.urls导入url中的,将
包含在项目的urls.py文件中,并将从django.urls导入url
更改为从django.conf.urls中导入基本应用程序的urls.py文件中的url
,并且在views.py中出现2个其他错误-
无法导入'rest_framework.decorators'
和无法导入'rest_framework.response'
.我不知道,为什么会出现这么多错误,因为我试图按照教程中的每个步骤进行操作.(注意:这两个错误是通过与此SO post一起解决的-
HomeScreen.js-
从"react"导入React,{useState,useEffect};从"react-bootstrap"导入{Row,Col};从"../components/Product"导入产品;从"axios"导入axios函数HomeScreen(){const [产品,setProducts] = useState([])useEffect(()=> {异步功能fetchProducts(){const {data} =等待axios.get('http://127.0.0.1:8000/api/products/')setProducts(数据)}fetchProducts()},[])返回 (< div>< h1>最新产品</h1><行>{products.map((product)=>(<颜色键= {product._id} sm = {12} md = {6} lg = {4} xl = {3}><产品product = {product}/></Col>))}</行></div>);}导出默认的HomeScreen;
views.py-
来自django.shortcuts的导入渲染从django.http导入JsonResponse从rest_framework.decorators导入api_view从rest_framework.response导入响应从.products进口产品#在这里创建您的视图.@api_view(['GET'])def getRoutes(request):路线= ['/api/products/','/api/products/create/','api/products/upload/','api/products/< id>/reviews/','api/products/top/','api/products/< id>/','api/products/delete/< id>/','api/products/< update>/< id>/',]返回响应(路线)@api_view(['GET'])def getProducts(要求):返回响应(产品)@api_view(['GET'])def getProduct(request,pk):产品=无对于产品中的我:如果i ['_ id'] == pk:产品=我休息返回响应(产品)
基本(应用程序)文件夹中的urls.py-
django.urls导入路径中的从 .导入视图urlpatterns = [path('',views.getRoutes,name ="routes"),path('products/',views.getProducts,name ="products"),path('products/< str:pk>/',views.getProduct,name ="product"),]
项目文件夹中的urls.py-
来自django.contrib的导入管理员从django.urls导入路径,包括urlpatterns = [路径("admin/",admin.site.urls),path('api/',include('base.urls')),]
解决方案import React,{useState,useEffect} from"react";从"react-bootstrap"导入{Row,Col};从"../components/Product"导入产品;从"axios"导入axios函数HomeScreen(){const [产品,setProducts] = useState([])useEffect(()=> {异步功能fetchProducts(){const response =等待axios.get('http://127.0.0.1:8000/api/products/').then((data)=> setProducts(data.data))}fetchProducts()},[])返回 (< div>< h1>最新产品</h1><行>{products.map((product)=>(<颜色键= {product._id} sm = {12} md = {6} lg = {4} xl = {3}><产品product = {product}/></Col>))}</行></div>);}导出默认的HomeScreen;
This post is the first part of the following series -
- A large number of problems with React, Django, Django REST and Axios
- Products on the homepage are not being displayed properly (Django, Django Rest and React)
- (React and Django) Displaying products on the homepage is working fine, but when I click on any particular product, then the rendering is wrong
I am going through a very good course about setting up an e-shop, but I have reached the stage, where I am not that much sure, what is the exact purpose of the code, which I have written. (especially the async function in HomeScreen.js) We are using React and Django. My issue is related to the homepage or HomeScreen.js file, which was working fine, when I was loading the products from the static products.json file, but later on, in the course, we had to switch this and load the products from an API using Django REST and Axios (axios was used to remove the CORS error) and my problem now is, that I am not able to load the products to the HomeScreen.js and all I see is a blank page with the header instead of a full page. I am running the react server through the npm start command (the result of that can be seen on the screenshots below) but I also tried to run the Django server, which gives me this error - OSError: [WinError 123]. (Note: the Django server was fixed and is now running - so when I want to display the website, I am running React server and Django server simultaneously)
Please let me know if You can see some solution to these problems. Thank You very much for any help in advance.
The page looks like this -
And it should look like this -
(Note: this problem with displaying of the products was solved by modyfying the urls.py in the base (app) folder -
from django.urls import path from . import views urlpatterns = [ path('', views.getRoutes, name="routes"), path('products/', views.getProducts, name="products"), path('products/<str:pk>/', views.getProduct, name="product"), ]
was changed to
from django.conf.urls import url from . import views urlpatterns = [ url('products/', views.getProducts, name="products"), url('products/<str:pk>/', views.getProduct, name="product"), url('routes/', views.getRoutes, name="routes"), ]
)
When I am looking to my console, I am getting a lot of errors such as - (not all of these errors are harmful, because for example the one relating to the collapseOnSellect was there even in the before all of the other errors have shown up and everything was working fine)
127.0.0.1:8000/api/products/:1 Failed to load resource: net::ERR_CONNECTION_REFUSED
Here are more details about the third error in the console -
(Note: This error has vanished after solving the following (path related and rest related) errors)
Another problem is, that VSCode is giving me these 2 errors -
No name 'path' in module 'django.urls'
andNo name 'include' in module 'django.urls'
(these errors are related to the both urls.py files)(Note: these errors were solved by changing
path
tourl
(in both urls.py files) and changingfrom django.urls import url, include
tofrom django.conf.urls import url, include
in the project´s urls.py file and changingfrom django.urls import url
tofrom django.conf.urls import url
in base application´s urls.py file)and I am getting 2 additional errors in the views.py -
Unable to import 'rest_framework.decorators'
andUnable to import 'rest_framework.response'
. I do not know, why am I getting so many errors, because I am trying to follow every step in the tutorial.(Note: these two errors were solved in conjuction with this SO post - Can't import: 'unable to import rest_framework' when importing serializer? (windows))
I am sorry, if my description of the problem is not exact, because I am still just a beginner when it comes to Django and React and so on. But I might explain to You further if You ask me the right questions. I have installed Axios accordingly to the tutorial and I have integrated it into the settings.py file.
Both of the frontend and backend folders are situated in the same folder.
HomeScreen.js -
import React, { useState, useEffect } from "react"; import { Row, Col } from "react-bootstrap"; import Product from "../components/Product"; import axios from "axios" function HomeScreen() { const [products, setProducts] = useState([]) useEffect(() => { async function fetchProducts() { const { data } = await axios.get('http://127.0.0.1:8000/api/products/') setProducts(data) } fetchProducts() },[] ) return ( <div> <h1>Latest Products</h1> <Row> {products.map((product) => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> </div> ); } export default HomeScreen;
views.py -
from django.shortcuts import render from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response from .products import products # Create your views here. @api_view(['GET']) def getRoutes(request): routes = [ '/api/products/', '/api/products/create/', 'api/products/upload/', 'api/products/<id>/reviews/', 'api/products/top/', 'api/products/<id>/', 'api/products/delete/<id>/', 'api/products/<update>/<id>/', ] return Response(routes) @api_view(['GET']) def getProducts(request): return Response(products) @api_view(['GET']) def getProduct(request, pk): product = None for i in products: if i['_id'] == pk: product = i break return Response(product)
urls.py in the base (app) folder -
from django.urls import path from . import views urlpatterns = [ path('', views.getRoutes, name="routes"), path('products/', views.getProducts, name="products"), path('products/<str:pk>/', views.getProduct, name="product"), ]
urls.py in the project folder -
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('base.urls')), ]
解决方案import React, { useState, useEffect } from "react"; import { Row, Col } from "react-bootstrap"; import Product from "../components/Product"; import axios from "axios" function HomeScreen() { const [products, setProducts] = useState([]) useEffect(() => { async function fetchProducts() { const responce = await axios.get('http://127.0.0.1:8000/api/products/') .then((data) => setProducts(data.data) )} fetchProducts() },[] ) return ( <div> <h1>Latest Products</h1> <Row> {products.map((product) => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> </div> ); } export default HomeScreen;
这篇关于React,Django,Django REST和Axios存在大量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!