我正在开发一个电子商务项目,我使用 Django 作为后端,使用 ReactJS 作为前端。但是,当我尝试从 ReactJS 组件获取数据到 Django 后端时遇到错误。浏览器控制台中出现错误消息“无法加载资源:服务器响应状态为 404(未找到)”。
以下是相关代码片段的简要概述:
在 Django 的
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
序列化器.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)
和urls.py:
path('api/farmers/register', FarmerRegistrationView.as_view(), name='farmer-register'),
在 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;
尽管在 Django 中正确设置了 URL 路由,并在 ReactJS 组件的 axios POST 请求中使用相同的 URL 路径,但我仍然遇到 404 错误。我检查了浏览器开发者工具中的网络选项卡,它显示对
/api/farmers/register
的请求返回了404状态。
我已经验证 Django 后端运行正常并且其他 API 端点可以访问。该问题似乎特定于此特定端点。
如果您能提供有关如何解决此错误并成功从 ReactJS 组件获取数据到 Django 后端的任何见解或建议,我将不胜感激。谢谢!
在浏览器控制台中:
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>
请把你在反应端调用的绝对url我的意思是(base_url + Route_name)像这样......
192.168.1.30:8000/api/farmers/register