[英]How to pass formData and body parameters in axios post request
i want to pass formdata and data in body parameter in axios post request, i tried some way but its not working.我想在 axios post 请求中传递 body 参数中的 formdata 和 data,我尝试了一些方法但它不起作用。 //code
//代码
const form = new FormData();
form.append("file", this.state.selectedFile);
const data={
token:localStorage.getItem('token'),
}
axios.post('http://localhost:3000/api/upload',form, {
onUploadProgress: ProgressEvent => {
this.setState({
loaded: (ProgressEvent.loaded / ProgressEvent.total*100),
})
},
})
.then(response=>{
console.log(response)
}).then(res => {
toast.success('upload success')
})
.catch(err => {
toast.error('upload fail')
})
You need to provide valid headers for respective content type您需要为相应的内容类型提供有效的标题
axios({ method: 'post', url: 'http://localhost:3000/api/upload', data: form, headers: {'Content-Type': 'multipart/form-data' } })
You are trying to pass a file in FormData which is not possible and you need to use FormUrlEncoded.您试图在 FormData 中传递一个文件,这是不可能的,您需要使用 FormUrlEncoded。 To do so you also need to install a npm package named query-string and then your data property would look something like this:
为此,您还需要安装一个名为 query-string 的 npm 包,然后您的数据属性将如下所示:
import qs from 'query-string';
...
axios.post(..., data:qs.stringify({
file: this.state.selectedFile
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.