I have an API to add a item in my database that works in Postman, in Agular I made a form for input data that when I submit it it sends a JSON with data. The problem is that the code works just fine until some time ago when i tried to add a new item and I get error code status 400 but i can't figure from where is the mistake. I'll let here the relevant code, if you have any questions please let me know, i'll try to answer as fast as I can. Thanks for help!
Angular Service
addItem(item:FormData):Observable<any>{ //itemAdd
return this.http.post<ItemAdd>(this.url+this.endpoint,item);
}
Item and form definition
addItemForm = new FormGroup({
brand: new FormControl(''),
name: new FormControl(''),
serialNumber: new FormControl(''),
price: new FormControl(''),
generalCategory: new FormControl(''),
category: new FormControl(''),
descriere: new FormControl(''),
quantity: new FormControl(''),
percentageSale: new FormControl(''),
image: new FormControl('')
});
item: ItemAdd = {
brand: "",
name: "",
serialNumber: "",
price: "",
generalCategory: "",
category: "",
descriere: "",
quantity: "",
percentSale: "",
image: []
}
Item add function
addItem() {
this.item.brand = this.addItemForm.value.brand;
this.item.name = this.addItemForm.value.name;
this.item.serialNumber = this.addItemForm.value.serialNumber;
this.item.price = this.addItemForm.value.price;
this.item.generalCategory = this.addItemForm.value.generalCategory;
this.item.category = this.addItemForm.value.category;
this.item.descriere = this.addItemForm.value.descriere;
this.item.quantity = this.addItemForm.value.quantity;
this.item.percentSale = this.addItemForm.value.percentageSale;'' +
const itemFormData = this.createFormData(this.item)
this.dialService.addItem(itemFormData).subscribe(response => {
this.dialogRef.close();
this.toast.showToast("Item succesfully created", "info");
console.log("item added")
console.log(response);
});
}
Create form data function
createFormData(item: ItemAdd): FormData {
const formData = new FormData();
formData.append('item',
new Blob([JSON.stringify(item)], {type: 'application/json'}));
for (var image = 0; image < item.image.length; image++) {
formData.append('image',
item.image[image].file,
item.image[image].file.name)
}
return formData;
}
HEADERS
Request URL: http://localhost:8081/api/items
Request Method: POST
Status Code: 400
Remote Address: [::1]:8081
Referrer Policy: strict-origin-when-cross-origin
Response Headers
access-control-allow-methods: PUT, GET, HEAD, POST, DELETE, OPTIONS
access-control-allow-origin: http://localhost:4200
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: close
Content-Type: application/json
Date: Sat, 08 Apr 2023 13:25:15 GMT
Expires: 0
Pragma: no-cache
Transfer-Encoding: chunked
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Request Headers
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ro-RO,ro;q=0.9,en-US;q=0.8,en;q=0.7
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbkB5YWhvby5jb20iLCJpYXQiOjE2ODA5NDk0ODcsImV4cCI6MTY4MTEyMjI4N30.nZgaAbjFRYZNZFsfHGoA9DrTLCUuC4N26q5VtXovS1g
Connection: keep-alive
Content-Length: 473142
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryw60j7sVWdlQukUvr
Host: localhost:8081
Origin: http://localhost:4200
Referer: http://localhost:4200/
sec-ch-ua: "Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36
BackEnd Code in case it's needed
@PostMapping("/items")
public Item createItem(@RequestPart("item") ItemAddDTO item,@RequestPart("image") MultipartFile file) throws IOException { //@RequestPart("image") MultipartFile file
return itemService.saveItem(item,file);
}
public Item saveItem(ItemAddDTO itemAddDTO,MultipartFile file) throws IOException {
Item item = this.modelMapper.map(itemAddDTO, Item.class);
item.setDateOfAdd(new Date());
item.setImage(imageService.uploadImageToFile(file));
itemRepository.save(item);
return item;
}
On the backend I get this error when make the call :"2023-04-08 16:25:15.806 WARN 4744 --- [nio-8081-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type com.example.backendapp.entities.Image
from Array value (token JsonToken.START_ARRAY
); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type com.example.backendapp.entities.Image
from Array value (token JsonToken.START_ARRAY
) at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 151] (through reference chain: com.example.backendapp.DTOs.ItemAddDTO["image"])]
"
I verified all parameters name, all API call all endpoints, it's everything as it should be, I even tried to remove the image upload because on backend it was saying that can't deserialize value of type image but stil does not work, I specify that from Postman everything it's ok all works with image input and in frontend all other call work perfecty exect add item and update item and I can't figure why. Thank you for reading this and I hope someone will see my mistake! Good day!