I have axios get request that I'm using to get an item for a mongodb collection in a vue project
async created() {
try {
const res = await axios.get(`http://localhost:3002/backend/gettestbyname`, {
name: "user language check numbers in different languages"
})
this.items = res.data;
this.imagesref = res.data[0].refimages;
this.imagestest = res.data[0].testimages;
this.imagesresult = res.data[0].testresults;
for (let i of this.imagesref){
this.expref.push(false);
this.exptest.push(false);
this.expres.push(false);
}
this.loadAPI=true;
} catch (error) {
console.log(error);
}
And this is the get request in my api
gettestbyname:function(req,res){
console.log(req.body.name);
scetest.find({name:req.body.name}).exec(function(err,report){
if(err){
res.json({message:'error',status:500,data:null})
}
else{
res.json({message:'report in system',status:200,data:report})
}
})
}
When I test the request in Postman using raw json data example: { "name": "name of item" }
I get the item but in my app im getting an empty data array
I'm thinking that something is wrong with the way i'm adding the param in the axios request
EDIT
after some debugging I noticed that my get request is getting executed twice in my app.
First execution is giving me the right result and the req.body.name is getting passed as a parameter second execution is just executing the get request with no parameter.
My app is saving only the last request I believe. This is what I got after console logging the req.body qnd the result in the request
{ name: 'user language check numbers in different languages' }
[
{
_id: new ObjectId("624c181587bdfbab1ee80cda"),
name: 'user language check numbers in different languages',
tag: '@DHRD-52484',
status: 'skipped/pending',
refimages: [],
testimages: [],
testresults: [],
__v: 0
}
]
{}
[]
You may need to specify a content-type
header
const reponse = await axios({
method: 'GET',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({
name: 'user language check numbers in different languages'
}),
url: 'http://localhost:3002/backend/gettestbyname',
})
But it should work. Also, be sure to validate your inputs! Perhaps you removed it for brevity but
console.log(req.body.name);
scetest.find({name:req.body.name}).exec(function(err,report){ ... })
The name
field needs to be validated and not just accepted directly from the body. If the caller puts an object in there it could alter your query in unexpected ways, definitely don't just pass it straight through to your query function.