使用Axios发送FormData时遭遇entity.parse.failed错误求助
使用Axios发送FormData请求时遭遇400错误
Axios返回的错误详情
{ "errors": { "expose": true, "statusCode": 400, "status": 400, "body": "----------------------------524246740682154737031830\r\nContent-Disposition: form-data; name=\"proposalData\"\r\n\r\n{// my data is here}\r\n----------------------------524246740682154737031830--\r\n", "type": "entity.parse.failed" } }
需求与现有代码
接口要求请求体必须为FormData格式,其中proposalData需是序列化后的JSON对象,请求体结构如下:
{ proposalData: { id_quotation_proposal: number; id_vehicle: number; id_address: number; renavam: string; billingType: string; comission: number; value: number; client: { name: string; cpf: string; phone: string; email: string; gender: number; birthdate: string; }; creditCard: {}; // 非必填 }; vehicleInvoice: Buffer;// 非必填 vehicleDocument: Buffer;// 非必填 }
数据准备代码
const body = await req.json(); const formData = new FormData(); formData.append('proposalData', JSON.stringify(body.proposalData));
初始Axios请求代码
const response = await axios.post(url, formData, { headers: { Authorization: token, }, });
已尝试的调整方案
- 合并FormData自动生成的请求头:
const response = await axios.post(url, formData, { headers: { Authorization: token, ...formData.getHeaders() }, });
- 手动指定Content-Type:
headers: { Authorization: token, "Content-Type": "multipart/form-data" },
补充信息
- 使用Insomnia发送相同结构的请求可正常返回结果
- 使用已废弃的
request-promise库发送请求时也能正常工作,代码如下:
import request from 'request-promise' // 其他代码 try{ const response = await request({ method: 'POST', uri: url, headers: { Authorization: token, ...formData.getHeaders(), }, body: formData, resolveWithFullResponse: true, }); // 其他代码
内容的提问来源于stack exchange,提问作者Kaique Roque
相关产品推荐
相关产品推荐

