我正在嘗試使用 axios 發布請求通過反應 js 組件創建產品。
在 django 日志中,我看到一個 OPTION 請求獲得 200 狀態代碼,但資料未保存在資料庫中。
通過郵遞員執行此操作時,它作業正常,這讓我認為問題出在 axios 請求中。
模型.py
class Product(models.Model):
title = models.CharField(max_length=32)
notes = models.TextField()
picture = models.ImageField(upload_to='product_images', null=True, blank=True)
amount = models.IntegerField(default=0)
@receiver(post_save, sender='product.Transaction')
def update_amount(sender, **kwargs):
product = Product.objects.get(title=kwargs['instance'].product)
if kwargs['instance'].transaction_type == 'IN':
product.amount = kwargs['instance'].amount
product.save()
else:
if product.amount - kwargs['instance'].amount > 0:
product.amount = product.amount - kwargs['instance'].amount
product.save()
def __str__(self):
return self.title
視圖.py
class ProductCreateView(generics.CreateAPIView):
serializer_class = ProductSerilizer
permission_classes = (permissions.IsAuthenticated,)
queryset = Product.objects.all()
序列化程式.py
class ProductSerilizer(ModelSerializer):
class Meta:
model = Product
fields = '__all__'
設定.py
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'product',
'rest_framework',
'corsheaders',
'rest_framework.authtoken'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DATETIME_FORMAT': '%d-%m-%Y',
}
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
添加產品.js
import React, {useState} from 'react';
import axios from 'axios'
import { useNavigate } from "react-router-dom";
function AddProduct() {
const [medicineTitle, setMedicineTitle] = useState('');
const [description, setDescription] = useState('');
const [medicineImage, setMedicineImage] = useState('');
const navigate = useNavigate();
const addToForm = async () => {
let formfield = new FormData()
formfield.append('title', medicineTitle)
formfield.append('notes', description)
formfield.append('picture', medicineImage)
formfield.append('amount', 0)
await axios({
method: 'post',
url: 'http://127.0.0.1:8000/api/protuct_create',
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': 'Token ********************************',
},
data: formfield,
}).then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
}
return (
<div className='container'>
<h5>Agregar un medicamento</h5>
<form encType='multipart/form-data' >
<div className="mb-3">
<label className="form-label">Nombre del medicamento</label>
<input
type="text"
className="form-control"
id="title"
aria-describedby="title"
placeholder='Introduce nombre del medicamentos'
name='title'
value={medicineTitle}
onChange={(e) => setMedicineTitle(e.target.value)}
/>
</div>
<div className="mb-3">
<label className="form-label">Descripción</label>
<textarea
className="form-control"
id="medicineDescription"
placeholder='Introduce una descripción'
name="medicineDescription"
aria-describedby="Description"
onChange={(e) => setDescription(e.target.value)}
>
</textarea>
</div>
<div className="mb-3">
<label className="form-label">Foto </label><br/>
<input
type="file"
className="form-control"
id="image"
aria-describedby="image"
placeholder='Selecciones la imagen'
name='image'
value={medicineImage}
onChange={(e) => setMedicineImage(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary" onClick={addToForm}>Submit</button>
</form>
</div>
);
}
export default AddProduct;
uj5u.com熱心網友回復:
我能夠弄清楚這一點。
問題與 CORS 標頭有關。我必須設定 API 允許的標頭。
通過在 django 后端添加以下代碼我的settings.py,它允許從前端發送的請求:
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433708.html
