我试图通过带有axios的React本机多步骤表单将数据提交到具有api平台的symfony后端。
我使用axios来处理这样的请求:
const contactProject = new FormData()
contactProject.append('propertyType', defaultpropretyType)
contactProject.append('budget', budget)
contactProject.append('surface', surface)
contactProject.append('nbRooms', rooms)
contactProject.append('tradeOperationType', defaultOperation)
然后,我将带有axios帖子的对象发送到api,如下所示:
axios
.post(`${API.URL}/contact_projects`, contactProject, {
headers: {
Authorization: `Bearer ${this.props.token}`,
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
console.log('LA REPONSE DE POST CONTACT PROJECT')
console.log(response)
})
.catch(error => {
console.log('ERROR POST CONTACT PROJECT')
console.log(contactProject)
console.log(error)
})
我要发送到api的表单数据对象是这样的:
FormData {
"_parts": Array [
Array [
"propertyType",
"maison",
],
Array [
"budget",
"0",
],
Array [
"surface",
5,
],
Array [
"nbRooms",
5,
],
Array [
"tradeOperationType",
"/trade_operation_types/1",
],
],
}
这就是为什么我会收到406错误,我需要发送一个纯json对象,所以如何将FormData转换为json?
只需发送。对于您的情况:
const contactProject={
propertyType: defaultpropretyType,
...
}
axios
.post(`${API.URL}/contact_projects`, contactProject, {
headers: {
Authorization: `Bearer ${this.props.token}`,
'Content-Type': 'application/json'
}
})