Reputation: 511
hi I am trying to post a multipart data in my react app using axios, but it's not not getting posted and giving me the error after taking a long time nearly about more then 5 minutes "(failed) net:::err_CONNECTION_RESET, i don't know what is going wrong here, below is the code snippet
function that makes the reqeuset :
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 ??
Upvotes: 0
Views: 736
Reputation: 21124
You can't post JSON data along with the file or any other attachment. You can post it as form data to your back end. The form data is passed as a multi-part data to the server with relevant boundaries. Here's a sample code for your reference. You may pass json data along with the formData as key, value pairs like this.
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));
Hope this helps. Happy Coding !
Upvotes: 1