使用axios发送FormData数据时,需要将axios的默认请求头设置为"Content-Type": "multipart/form-data",并将FormData作为请求体传递给axios。
以下是示例代码:
import axios from 'axios';
const formData = new FormData();
formData.append('name', 'John');
formData.append('email', 'john@example.com');
axios.defaults.headers.common['Content-Type'] = 'multipart/form-data';
axios.post('/api/url', formData)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
在上述代码中,我们首先创建了一个FormData对象,并向其添加了一些数据。然后,我们将axios的默认请求头设置为"Content-Type": "multipart/form-data",以确保后端正确解析FormData数据。最后,我们使用post方法将FormData作为请求体发送给服务器,并在then回调函数中处理服务器的响应或在catch回调函数中处理错误。
请确保替换示例代码中的"/api/url"为实际的后端接口URL。