This question already has answers here:
javascript says JSON object property is undefined although it's not
(4 answers)
Closed 3 years ago.
Trying to make a http request with axios, then accessing some property from request. Property is undefined, although it is present
public getApiURL() {
axios.get('https://xxxxxxxxx.com/metadata.json')
.then(res => {
console.log(res.data); // {"apiUrl":"https://xxxx.com/Api"}
console.log(res.data.apiUrl); // undefined
}).catch(err => {
console.log('error', err);
})
}
Try This one
`
public getApiURL=async ()=> {
try{
let result= await axios.get('https://xxxxxxxxx.com/metadata.json')
const data = JSON.parse(result.data);
console.log(data.apiUrl);
}catch(err){
console.log(err);
}
}
`
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 28 days ago.
I am new to Javascript. I am trying to retrieve data from a MQTT broker through an async JavaScript function, querydevice. Here I am successfully getting a response from functions.logger.log(`Query msg retrived from MQTT ${msg}`) as expected.
const querydevice = async () => {
let msg;
try {
await client.subscribe("test/result");
client.on('message', function(topic, message) {
msg = message.toString();
var tp = topic.toString();
client.end();
functions.logger.log(
`Query msg retrived from MQTT ${msg}`
);
});
return {
state: msg,
}
} catch (e) {
process.exit();
}
};
I am calling the function querydevice in another function called app.onQuery as below. But I am not getting a correct response in functions.logger.log(`Device state:${dt.state}`). It shows undefined in place of the dt.state variable in the logs.
app.onQuery(async (body) => {
const dt = await querydevice();
functions.logger.log(`Device state:${dt.state}`);
return {
requestId: body.requestId,
payload: {
devices: {
"OOB-Group-7": {
on: false,
online: true
}
}
}
}
});
Can some one guide me where I am doing wrong?
I tried removing await, used .then instead in app.onQuery function. Also I tried .toString() for the dt variable.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 months ago.
Main function
export async function postData(TVMID) {
const data = await FetchingData(TVMID)
// regex the year
const rex = /^[0-9]{4}/g;
let country;
let network;
let geners = await CheckGenderIfExist(data.genres).then(genx => genx)
more code....
}
Check if data exist function
export async function CheckGenderIfExist(genders) {
let listOfGenders = [];
if (Array.isArray(genders)) {
genders.forEach(gen => {
axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api/genders?filters[$and][0][Name][$eq]=${gen}`)
.then((response) => {
if (response.data.data.length == 0) {
AddTVGenders(gen)
} else {
listOfGenders.push(response.data.data[0].id)
}
});
})
} else {
axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api/genders?filters[$and][0][Name][$eq]=${genders}`)
.then((response) => {
listOfGenders.push(response.data.data[0].id)
});
}
return listOfGstenders;
}
Add missing data function
export async function AddTVGenders(gen) {
await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/api/genders`, {
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`,
},
"data": {
Name: gen,
}
})
CheckGenderIfExist(gen)
}
Im' using strapi v4.5 with nextjs v13, while tring to post data for some of the relation fields , i have to check if the data exist if not, i create it then get the id then add it to the main post function
This is what i came up with but it return empty array
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a nodejs app and I am trying to pass a value called membership to a page. I initialize it and try to update its value in a function but the output doesn't change. It still outputs 0. Please I need help
app.get("/",(req,res)=>{
var membershipStrength = 0;
memberData.findAll()
.then(members =>{
// console.log(members.length);
membershipStrength = members.length;
console.log(membershipStrength);
})
.catch(err => {
console.log("Error fetching members data: ", err);
});
console.log(membershipStrength);
return res.render("index",
{
page: "Admin",
membershipStrength: membershipStrength,
// tableData : global.dataOut
}
);
});
You're calling the render function before the call to findAll completes. Thus, when your server responds to the HTTP request, it still has the original value of membershipStrength in it.
You need to put the call to render inside the then handler:
app.get("/",(req,res)=>{
var membershipStrength = 0;
return memberData.findAll()
.then(members =>{
// console.log(members.length);
membershipStrength = members.length;
console.log(membershipStrength);
return res.render("index",
{
page: "Admin",
membershipStrength: membershipStrength,
// tableData : global.dataOut
}
);
})
.catch(err => {
console.log("Error fetching members data: ", err);
});
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a server-side function that outputs a value from a database to /.netlify/functions/todos-read
I need to read it on another page, however the read() function returns undefined instead.
Here is what i tried:
function read() {
fetch('/.netlify/functions/todos-read').then(res => res.json()).then((out) => {
return out
}).catch(err => console.error(err));
}
Here is what i expected it to return:
{"ref":{"#ref":{"id":"236323245287014920","class":{"#ref":{"id":"nappi","class":{"#ref":{"id":"classes"}}}}}},"ts":1561634259400000,"data":{"value":1}}
Your read() function should return a promise, and callers should expect one...
function read() {
return fetch('/.netlify/functions/todos-read').then(res => res.json());
}
// call it
read().then(res => {
console.log(res);
}).catch(error => {
console.log(error);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
This is the problem
This is the script
var data = [];
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(function (response) {
data.push(response.data['0'])
})
.catch(function (error) {
console.log(error);
});
console.log(data);
console.log(data['0'].body); //this is where I get the error
As you can see in the picture it should be correct but why I cannot read the property ?
Are you sure the data object is filled when you try access it?
Does the following work?
var data = [];
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(function (response) {
data.push(response.data['0'])
console.log(data['0'].body);
})
.catch(function (error) {
console.log(error);
});
Your data is an array, so it must be accessed with integer like data[0].body.
String accessor might be useful for Object type, not array. For example, you can also do data[0][“body”].