Axios请求失败,状态码为406

时间:2019-10-16 07:29:54

标签: react-native axios form-data

我试图将带有axios的React本机多步骤表单中的数据提交到具有api平台的symfony后端。

我使用axios来处理这样的请求:

<string name="google_client_id">XXXXXXXXX.apps.googleusercontent.com</string>
<string name="default_web_client_id">XXXX-XXXXXX.apps.googleusercontent.com</string>
<string name="gcm_defaultSenderId">XXXXXX</string>
<string name="google_api_key">AIzaXXXXXX</string>
<string name="google_app_id">1:XXXXXX:android:XXXXX</string>
<string name="google_crash_reporting_api_key">AIzaXXXXXXX</string>
<string name="project_id">XXXXXXX</string>

然后我将带有axios帖子的对象发送到api:

    const contactProject = new FormData()
    contactProject.append('propertyType', defaultpropretyType)
    contactProject.append('budget', budget)
    contactProject.append('surface', surface)
    contactProject.append('nbRooms', rooms)
    contactProject.append('tradeOperationType', defaultOperation)

我要发送到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)
      })

这就是为什么我会收到406错误,我需要发送一个纯json对象,所以如何将FormData转换为json?

1 个答案:

答案 0 :(得分:1)

只发送它。 对于您的情况:

const contactProject={
propertyType: defaultpropretyType,
...
}
axios
      .post(`${API.URL}/contact_projects`, contactProject, {
        headers: {
          Authorization: `Bearer ${this.props.token}`,
          'Content-Type': 'application/json'
        }
      })