React、Django、Django REST 和 Axios 的大量问题 [英] A large number of problems with React, Django, Django REST and Axios

查看:33
本文介绍了React、Django、Django REST 和 Axios 的大量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章是以下系列的第一部分 -

  1. 它应该是这样的——

    (注意:通过修改基本(app)文件夹中的 urls.py 解决了显示产品的问题-

    from django.urls 导入路径从 .导入视图网址模式 = [path('', views.getRoutes, name="routes"),path('products/', views.getProducts, name="products"),path('products//', views.getProduct, name="product"),]

    改为

    from django.conf.urls 导入 url从 .导入视图网址模式 = [url('products/', views.getProducts, name="products"),url('products//', views.getProduct, name="product"),url('routes/', views.getRoutes, name="routes"),]

    )

    当我查看我的控制台时,我收到了很多错误,例如 -(并非所有这些错误是有害的,因为例如与 collapseOnSellect 相关的那个甚至在所有其他错误出现之前就已经存在并且一切正常)

    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 文件中)并更改 from django.urls import url 来解决的,包括from django.conf.urls import url,include 在项目的 urls.py 文件中,将 from django.urls import url 改为 from django.conf.urls import url in base application's urls.py 文件)

    并且我在 views.py 中收到 2 个额外的错误 - 无法导入 'rest_framework.decorators'无法导入 'rest_framework.response'.我不知道,为什么我会收到这么多错误,因为我正在尝试按照教程中的每一步进行操作.

    (注意:这两个错误已与此 SO 帖子结合解决 -

    HomeScreen.js -

    import React, { useState, useEffect } from "react";从react-bootstrap"导入{行,列};从../components/Product"导入产品;从axios"导入 axios功能主屏幕(){const [products, setProducts] = useState([])useEffect(() => {异步函数 fetchProducts() {const { data } = await axios.get('http://127.0.0.1:8000/api/products/')设置产品(数据)}fetchProducts()},[] )返回 (<div><h1>最新产品</h1><行>{products.map((product) => (<Col key={product._id} sm={12} md={6} lg={4} xl={3}><产品产品={产品}/></Col>))}</行>

);}导出默认主屏幕;

views.py -

from django.shortcuts 导入渲染从 django.http 导入 JsonResponse从 rest_framework.decorators 导入 api_view从 rest_framework.response 导入响应from .products 进口产品# 在此处创建您的视图.@api_view(['GET'])def getRoutes(请求):路线 = ['/api/产品/','/api/产品/创建/','api/产品/上传/','api/products//reviews/','api/产品/顶部/','api/products//','api/products/delete//','api/products/<更新>//',]返回响应(路由)@api_view(['GET'])def getProducts(请求):退货响应(产品)@api_view(['GET'])def getProduct(请求,pk):产品 = 无对于 i 在产品中:如果 i['_id'] == pk:产品=我休息返回响应(产品)

基本(应用)文件夹中的 urls.py -

from django.urls 导入路径从 .导入视图网址模式 = [path('', views.getRoutes, name="routes"),path('products/', views.getProducts, name="products"),path('products//', views.getProduct, name="product"),]

项目文件夹中的urls.py -

from django.contrib import admin从 django.urls 导入路径,包括网址模式 = [路径('管理员/',admin.site.urls),path('api/', include('base.urls')),]

解决方案

import React, { useState, useEffect } from "react";从react-bootstrap"导入{行,列};从../components/Product"导入产品;从axios"导入 axios功能主屏幕(){const [products, setProducts] = useState([])useEffect(() => {异步函数 fetchProducts() {const 响应 = 等待 axios.get('http://127.0.0.1:8000/api/products/').then((data) => setProducts(data.data))}fetchProducts()},[] )返回 (<div><h1>最新产品</h1><行>{products.map((product) => (<Col key={product._id} sm={12} md={6} lg={4} xl={3}><产品产品={产品}/></Col>))}</行>

);}导出默认主屏幕;

This post is the first part of the following series -

  1. A large number of problems with React, Django, Django REST and Axios
  2. Products on the homepage are not being displayed properly (Django, Django Rest and React)
  3. (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' and No name 'include' in module 'django.urls' (these errors are related to the both urls.py files)

(Note: these errors were solved by changing path to url (in both urls.py files) and changing from django.urls import url, include to from django.conf.urls import url, include in the project´s urls.py file and changing from django.urls import url to from 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' and Unable 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屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆