Search code examples
reactjsdjango-rest-frameworkerror-handlingaxios

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. However, I am encountering an error when trying to fetch data from the ReactJS component to the Django backend. The error message "Failed to load resource: the server responded with a status of 404 (Not Found)" appears in the browser console.

Here is a brief overview of the relevant code snippets:

In Django's urls.py:

models.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:

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:

@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:

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

In the 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. 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.

I have verified that the Django backend is running correctly and other API endpoints are accessible. 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. 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>

Solution

  • 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