How to send form data in POST request in Nuxt 3 to django DRF
I am trying to use Nuxt 3 as a server to pass through API requests. I would like to make FormData requests to a Django DRF API through my Nuxt server to POST data and images.
basically, the usecase is filling a simple form with data and images and send the formdata to a django backend. Here are more details.
In pages.vue
:
const taskData = reactive({
title: '',
city: '',
description: '',
category: route.params.cat_slug,
subCat: '',
image_1: [],
image_2: [],
image_3: []
})
const submitTaskForm = async () => {
let formData = new FormData()
formData.append('title', taskData.title)
formData.append('city', taskData.city)
formData.append('description', taskData.description)
formData.append('category', taskData.category)
formData.append('subCat', taskData.subCat)
taskData.image_1.forEach((fileItem) => {
formData.append('image_1', fileItem.file)
})
taskData.image_2.forEach((fileItem) => {
formData.append('image_2', fileItem.file)
})
taskData.image_3.forEach((fileItem) => {
formData.append('image_3', fileItem.file)
})
const data = await useFetch('/api/tasks/add/', {
method: 'POST',
body: formData
})
return data
}
in /server/api/add.post.ts
export default defineEventHandler(async (event) => {
const body = await readBody(event)
const access = getCookie(event, 'access') || null
try {
const data = await $fetch(process.env.API_BASE_URL + "/api/tasks/add/", {
method: "POST",
body: body,
headers: {
Authorization: "Bearer " + access,
},
})
return data
} catch (error) {
console.log(error);
return error
}
})
now the backend part with the view handling the form:
class TasksCreate(APIView):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = TasksSerializer
parser_classes = [MultiPartParser, FormParser]
def post(self, request):
data = self.request.data
title = data['title']
city = data['city']
description = data['description']
category_slug = data['category']
subCat = data['subCat']
image_1 = request.FILES.get('image_1', "")
image_2 = request.FILES.get('image_2', "")
image_3 = request.FILES.get('image_3', "")
try:
if not Subcategories.objects.filter(slug=subCat, category__slug=category_slug).exists():
return Response(
{'error': 'The subcategory does not correspond to the category.', },
status=status.HTTP_400_BAD_REQUEST
)
task = Task.objects.create(
title=title,
city=city,
description=description,
slug='%s-%s' % (slugify(title), randint(1000, 10000)),
category=get_object_or_404(Category, slug=category_slug),
sub_category = get_object_or_404(Subcategories, slug=subCat),
created_by=request.user,
image_1=image_1,
image_2=image_2,
image_3=image_3,
)
task.save()
return Response(
{'task': 'Task created successfully', },
status=status.HTTP_201_CREATED
)
except Exception as e:
print(e)
return Response(
{'error': 'Something went wrong when creating the task'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
the error: Unsupported Media Type: /api/tasks/add/
I have tried with readBody
readRawBody
readMultipartFormData
and also adding "Content-Type": "multipart/form-data"
to headers.
Also, hitting directly the view with Postman work perfectly so my guess it's nuxt 3 not sending correctly the form.