英文:
415 error when sending objects and file to the server at once
问题
前端代码中的问题可能与数据格式有关,导致服务器返回415错误。您可以尝试以下修改来解决这个问题:
前端代码:
const headers = {
'Authorization': `Bearer ${token}`,
}
const handleFormSubmit = async (e) => {
const data = {
petname: e.petname,
age: e.age,
type: e.type,
weight: e.weight,
firstmet: e.firstmet,
};
const formData = new FormData();
formData.append("file", e.file[0]);
formData.append("request", JSON.stringify(data));
console.log(formData);
await axios.post("http://localhost:5000/api/pet/petform", formData, {
headers: {
...headers,
'Content-Type': 'multipart/form-data',
},
})
.then((response) => {})
.catch((error) => {})
}
后端代码:
@PostMapping(value = "/petform", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void save(@RequestPart("file") MultipartFile file, @RequestPart("request") String petDTOJson) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
PetDTO petDTO = objectMapper.readValue(petDTOJson, PetDTO.class);
// 接下来处理petDTO和file
}
主要更改包括前端代码中的headers
和formData
的构建方式,以及后端代码中对request
参数的处理方式。这些更改应该有助于正确处理文件和对象的同时发送,并避免415错误。
英文:
I want to send file and objects to the server at at once, but I get 415 error.
I use react-hook-form library
**frontend
**
const headers = {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${token}`,
}
const handleFormSubmit = async (e) => {
const data = [{
petname: e.petname,
age: e.age,
type: e.type,
weight: e.weight,
firstmet: e.firstmet
}];
const formData = new FormData();
formData.append("file", e.file[0]);
formData.append("request", new Blob([JSON.stringify(data)], {contentType:"application/json"}))
console.log(formData)
await axios.post("http://localhost:5000/api/pet/petform", formData, {
headers: headers
})
.then((response) => {})
.catch((error) => {})
}
**backend
**
@PostMapping(value = "/petform",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void save(@RequestPart(value="file", required = false) MultipartFile file,
@RequestPart(value="request", required = false) PetDTO petDTO) throws IOException {
}
**error code
**
Request failed with status code 415
When the parameter was sent to the postman, the spring boot was stamped normally.
答案1
得分: 1
你有一个数组在这里:
const data = [{
petname: e.petname,
age: e.age,
type: e.type,
weight: e.weight,
firstmet: e.firstmet
}];
应该是:
const data = {
petname: e.petname,
age: e.age,
type: e.type,
weight: e.weight,
firstmet: e.firstmet
};
以匹配请求。
英文:
You have an array here:
const data = [{
petname: e.petname,
age: e.age,
type: e.type,
weight: e.weight,
firstmet: e.firstmet
}];
Should be
const data = {
petname: e.petname,
age: e.age,
type: e.type,
weight: e.weight,
firstmet: e.firstmet
};
To match the request
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论