简体   繁体   English

Django 和 ReactJS 集成:“无法加载资源:服务器响应状态为 404(未找到)”错误

[英]Django and ReactJS integration: "Failed to load resource: the server responded with a status of 404 (Not Found)" error

I am working on an e-commerce project where I am using Django for the backend and ReactJS for the front end.我正在从事一个电子商务项目,我在后端使用 Django,在前端使用 ReactJS。 However, I am encountering an error when trying to fetch data from the ReactJS component to the Django backend.但是,我在尝试从 ReactJS 组件获取数据到 Django 后端时遇到错误。 The error message "Failed to load resource: the server responded with a status of 404 (Not Found)" appears in the browser console.浏览器控制台中出现错误消息“无法加载资源:服务器响应状态为 404(未找到)”。

Here is a brief overview of the relevant code snippets:以下是相关代码片段的简要概述:

In Django's urls.py :在 Django 的urls.py中:

models.py:模型.py:

class Farmer(models.Model):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
        ('O', 'Other'),
    )

    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=128)
    address = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    state = models.CharField(max_length=255)
    zip_code = models.CharField(max_length=10)
    phone_number = models.CharField(max_length=10)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    aadhaar_card = models.CharField(max_length=12)
    stripe_connect_id = models.CharField(max_length=255, blank=True)

    def __str__(self):
        return self.email

        
    def set_password(self, password):
        self.password = password

serializers.py:序列化器.py:

class FarmerRegistrationSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, style={'input_type': 'password'})

    class Meta:
        model = Farmer
        fields = ['first_name', 'last_name', 'email', 'password', 'address', 'city', 'state', 'zip_code',
                  'phone_number', 'gender', 'aadhaar_card']

    def validate(self, attrs):
        form = FarmerRegistrationForm(data=attrs)
        if form.is_valid():
            return attrs
        else:
            raise serializers.ValidationError(form.errors)

    def create(self, validated_data):
        form = FarmerRegistrationForm(data=validated_data)
        if form.is_valid():
            return form.save()
        else:
            raise serializers.ValidationError(form.errors)

views.py:意见.py:

@method_decorator(csrf_exempt, name='dispatch')
class FarmerRegistrationView(APIView):
    def post(self, request):
        serializer = FarmerRegistrationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

and urls.py:网址.py:

path('api/farmers/register', FarmerRegistrationView.as_view(), name='farmer-register'),路径('api/farmers/register', FarmerRegistrationView.as_view(), name='farmer-register'),

In the ReactJS FarmerRegistrationPage.js:在 ReactJS FarmerRegistrationPage.js 中:

import React, { useState } from 'react';
import axios from 'axios';
import './css/FarmerRegistrationPage.css';

const FarmerRegistrationPage = () => {
  const [formData, setFormData] = useState({
    first_name: '',
    last_name: '',
    email: '',
    password: '',
    address: '',
    city: '',
    state: '',
    zip_code: '',
    phone_number: '',
    gender: '',
    aadhaar_card: '',
  });

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      console.log('Form Data:', formData); // Debug: Log form data
      const response = await axios.post('/api/farmers/register', formData);
      console.log('Response:', response.data); // Debug: Log response data
      setFormData({ ...formData, first_name: '' }); // Update the reset state accordingly
      alert('Registration successful');
    } catch (error) {
      if (error.response) {
        console.log(error.response.data);
        if (error.response.status === 400) {
          // Handle specific validation errors
          alert('Registration failed: ' + error.response.data.error_message);
        } else {
          // Handle other server-side errors
          alert('Registration failed: ' + error.response.data.detail);
        }
      } else if (error.request) {
        console.log(error.request);
        alert('Registration failed: No response received from the server');
      } else {
        console.log('Error', error.message);
        alert('Registration failed: ' + error.message);
      }
    }
  };
  
  

  return (
    <div>
      <h2>Farmer Registration</h2>
      <form onSubmit={handleSubmit}>
        <label>
          First Name:
          <input
            type="text"
            name="first_name"
            value={formData.first_name}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <label>
          Last Name:
          <input
            type="text"
            name="last_name"
            value={formData.last_name}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <label>
          Email:
          <input
            type="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <label>
          Password:
          <input
            type="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <label>
          Address:
          <input
            type="text"
            name="address"
            value={formData.address}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <label>
          City:
          <input
            type="text"
            name="city"
            value={formData.city}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <label>
          State:
          <input
            type="text"
            name="state"
            value={formData.state}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <label>
          Zip Code:
          <input
            type="text"
            name="zip_code"
            value={formData.zip_code}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <label>
          Phone Number:
          <input
            type="text"
            name="phone_number"
            value={formData.phone_number}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <label>
          Gender:
          <select
            name="gender"
            value={formData.gender}
            onChange={handleChange}
            required
          >
            <option value="">Select</option>
            <option value="M">Male</option>
            <option value="F">Female</option>
            <option value="O">Other</option>
          </select>
        </label>
        <br />
        <label>
          Aadhaar Card Number:
          <input
            type="text"
            name="aadhaar_card"
            value={formData.aadhaar_card}
            onChange={handleChange}
            required
          />
        </label>
        <br />
        <button type="submit">Register</button>
      </form>
    </div>
  );
};
export default FarmerRegistrationPage;

Despite setting up the URL route correctly in Django and using the same URL path in the ReactJS component's axios POST request, I am still encountering the 404 error.尽管在 Django 中正确设置了 URL 路由,并在 ReactJS 组件的 axios POST 请求中使用相同的 URL 路径,但我仍然遇到 404 错误。 I have checked the.network tab in the browser's developer tools, and it shows that the request to /api/farmers/register returns a 404 status.我检查了浏览器开发工具中的.network 选项卡,它显示对/api/farmers/register请求返回了404 状态。

I have verified that the Django backend is running correctly and other API endpoints are accessible.我已验证 Django 后端运行正常,其他 API 端点可访问。 The issue seems to be specific to this particular endpoint.该问题似乎特定于此特定端点。

I would appreciate any insights or suggestions on how to resolve this error and successfully fetch data from the ReactJS component to the Django backend.对于如何解决此错误并成功将数据从 ReactJS 组件提取到 Django 后端,我将不胜感激。 Thank you!谢谢你!

In browser console:在浏览器控制台中:

Form Data: Object

:3000/api/farmers/register:1 

Failed to load resource: the server responded with a status of 404 (Not Found)

FarmerRegistrationPage.js:34 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/farmers/register</pre>
</body>
</html>

plz put absulate url which you called in react side i mean (base_url + route_name) like this... 192.168.1.30:8000/api/farmers/register请输入你在反应端调用的 absulate url 我的意思是 (base_url + route_name) 像这样... 192.168.1.30:8000/api/farmers/register

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ReactJS - 加载资源失败:服务器响应状态为 404(未找到) - ReactJS - Failed to load resource: the server responded with a status of 404 (Not Found) ReactJS Heroku 部署错误:无法加载资源:服务器响应状态为 404(未找到) - ReactJS Heroku Deployment Error: Failed to load resource: the server responded with a status of 404 (Not Found) 如何解决:加载资源失败:服务器在 Reactjs 中响应状态为 404(未找到) - How to resolve: Failed to load resource: the server responded with a status of 404 (Not Found) in Reactjs 404 Failed to load resource: 服务器响应状态为 404 (Not Found) Django React - 404 Failed to load resource: the server responded with a status of 404 (Not Found) Django React 如何解决此错误(加载资源失败:服务器响应状态为 404 ()) - how solve this error (Failed to load resource: the server responded with a status of 404 ()) Django 未正确路由资源“加载资源失败:服务器响应状态为 404(未找到)main.7ec538f6.chunk.js:1” - Django is not routing resource properly "Failed to load resource: the server responded with a status of 404 (Not Found) main.7ec538f6.chunk.js:1" 当我使用 axios 向服务器发送文件时,出现此错误“无法加载资源:服务器响应状态为 404(未找到)” - I'm getting this error " Failed to load resource: the server responded with a status of 404 (Not Found)" when i send a file to server using axios “加载资源失败:服务器响应状态为 404(未找到)”+“来源……访问控制允许来源不允许。” - "Failed to load resource: the server responded with a status of 404 (Not Found)" + "Origin … is not allowed by Access-Control-Allow-Origin." 节点js响应加载资源失败:服务器响应状态为404(未找到) - Node js response Failed to load resource: the server responded with a status of 404 (Not Found) 加载资源失败:在已部署的 React.js 项目中,服务器响应状态为 404(未找到) - Failed to load resource: the server responded with a status of 404 (Not Found) in React.js Project deployed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM