In a function, I have to insert a string into a data array, that is part of axios request call:
var obj1 = JSON.parse(payload);
axios.request({
url: inUrl,
method: "POST",
auth: {
username: auth,
password: pass
},
headers: { 'content-type': 'application/json' },
data: {
"success": inState,
"fails": inCount,
obj1
}
}).then(res => {
//console.log(res);
console.log("bucket commopn response: "+ res.status);
return "success";
}).catch(error => {
console.log(error);
console.log("bucket error reponse: " + error.response.status);
return "error";
});
payload is a pure string with the content:
{"branch":"CPL-1223"}
This was created from an object with
var payload = JSON.stringify(req.body.responsePayload);
How can I insert the new object into
data: {
"success": inState,
"fails": inCount,
obj1
}
To make a valid call? Because currently, whatever I do, I get from the Axios server a invalid body, if I make hand call
data: {
"success": inState,
"fails": inCount,
"branch":"CPL-1223"
}
I get a success back. What is my fault?
2 Answers 2
Inside your code you're trying to do this:
const obj = { branch: 'CPL-1223' }
const body = {
data: {
success: '',
fails: '',
obj
}
}
If you make a console.log on this constant body you will get this:
{
data: {
success: '',
fails: '',
obj: {
branch: 'CPL-1223'
}
}
}
So the mistake is that you're trying to insert whole object without spreding it. More information about spread syntax you can read here - Spread syntax
So to make body like this:
{
data: {
success: '',
fails: '',
branch: 'CPL-1223'
}
}
you should use spread operator ... and you will get the expected result.
const obj = { branch: 'CPL-1223' }
const body = {
data: {
success: '',
fails: '',
...obj
}
}
Do not afraid to use console.log! It is very powerfull tool that can help you to understand more.
Comments
data: {
"success": inState,
"fails": inCount,
obj1
}
In this code snippet you are attaching obj1 to data object as a nested sub object. But your use case is to have the contents of obj1 to be inserted inside data object. For that you can use the new spread operator (...).
You can fix your code by using the below code snippet -
data: {
"success": inState,
"fails": inCount,
...obj1
}
...obj1instead of justobj1in data.