嗨我正在尝试使用axios在我的反应应用程序中发布多部分数据,但它不会被发布并且在花了很长时间差不多5分钟之后给我错误"(失败了)net ::: err_CONNECTION_RESET,我不知道这里出了什么问题,下面是代码片段
制作请求的功能:
handleClick(event){
let self = this;
if(this.state.filesToBeSent.length>0){
const formData = new FormData();
formData.append('file',this.state.filesToBeSent[0][0]);
let jsonObject = new Object;
jsonObject.itemId="1262";
jsonObject.module="Breakfix";
jsonObject.filename=("yyyyy");
jsonObject.filepath="c:\\abc\\";
jsonObject.createdOn=Math.round(new Date().getTime()/1000.0);
jsonObject.createdBy="3";
formData.append("attachment", JSON.stringify(jsonObject));
let filesArray = this.state.filesToBeSent;
axios.post(GLOBAL.uploadFile,
formData
);
}
else{
alert("Please upload some files first");
}
}
**code written on express to route the post to the actual API** :
function uploadFiles(request, response) {
let payload = request.signedCookies['access_token'];
payload.apikey = "d2c-234";
const secret = 'my-secret';
const signed = jwt.sign(payload, secret, {
algorithm: 'HS256',
expiresIn: '7d'
});
let config = {
headers: {'x-auth-token': signed
}
};
let data={}
if(!_.isEmpty(request.body)) {
data = request.body;
}
axios.post("https://abc-myapp.net/serviceManagement/rest/uploadBreakfixImage/",data,config)
.then(uploadResponse => {
response.status(200).json(uploadResponse);
}).catch(function(error) {
console.error(error.stack);
});
}
when putting console on the express side it seems request doesn't have the payload, what am i doing wrong here ??
答案 0 :(得分:1)
您无法将JSON数据与文件或任何其他附件一起发布。您可以将其作为表单数据发布到后端。表单数据作为多部分数据传递给具有相关边界的服务器。这是一个示例代码供您参考。您可以将json数据与formData一起作为键值对传递。
let data = new FormData();
data.append('itemId', '1262');
data.append('module', 'Breakfix');
data.append('filename', 'yyyyy');
data.append('filepath', 'c:\\abc\\');
data.append('upload', fileData, fileName)
axios.post(url, data)
.then(response => console.log(response))
.catch(errors => console.log(errors));
希望这会有所帮助。快乐的编码!