Why I am getting error when calling the api using axios? - javascript

I want to call the api and use the api result for further computation But not able to do like this. Even after using async/await. I am getting the console value as undefined.I tried using promise aswell but I am not getting how do i give authorization atribute to it.
I am naive to js, can anyone help where I am going wrong?
var plan;
async function makeRequest() {
const config = {
"url": "https://jsonplaceholder.typicode.com/posts/1",
"method": "GET",
"timeout": 0,
"headers": {
"Authorization": "[Auth_url]"
},
};
let res = await axios(config)
console.log(res);
plan = res;
}
makeRequest();
console.log("plan",plan)
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

You can try this way
you can pass the token details in the headers section
var plan= [];
function makeRequest() {
axios.get('https://jsonplaceholder.typicode.com/posts/1', {
headers: {
/* 'Authorization': '',*/
}})
.then((res) => {
plan = res.data;
console.log(plan);
});
}
makeRequest();
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
This approach you can try in the sample snippet set you have provided.
var plan;
async function makeRequest() {
const config = {
"url": "https://jsonplaceholder.typicode.com/posts/1",
"method": "GET",
"timeout": 0,
"headers": {
"Authorization": "[Auth_url]"
},
};
let res = await axios(config)
plan = res.data;
}
makeRequest().then(result => {
console.log("plan",plan)
});
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Related

JavaScript skip await on pending fetch [duplicate]

This question already has answers here:
Fetch API request timeout?
(14 answers)
Closed 8 months ago.
I have an API fetch await code that fetches list of nodes in an array. The problem is, some of the nodes don't respond for whatever reason (being offline, wrong port, being programmed NOT to respond, ... ) and my code is stuck awaiting a reply from that node.
Is there any way to stop awaiting a fetch for example after 3 seconds if no response comes?
I tried using try and catch, but the nodes that don't respond don't return anything, the code is simply sitting there with no error or response.
Thank you!!
// list of nodes
let nodes = [{
"address": {
"hostname": "192.168.1.1",
"port": 31350
}
}, {
"address": {
"hostname": "192.168.1.2",
"port": 31350
}
}
]
// api fetch function
async function fetchNodes(hostname, port) {
const response = await fetch(`https://${hostname}:${port}/getstatus`, {
method: 'post',
body: JSON.stringify(body),
headers: {'Content-Type': 'application/json'}
});
const data = response.json();
console.log(data);
}
// loop to call api fetch function with all array entries
nodes.forEach(function(entry) {
fetchNodes(entry.address.hostname, entry.address.port);
}
)
try this
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 8000 } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal
});
clearTimeout(id);
return response;
}
and use this function in you fetchNodes function
async function fetchNodes() {
try {
const response = await fetchWithTimeout(
`https://${hostname}:${port}/getstatus`,
{
timeout: 6000,
method: "post",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
}
);
const data = await response.json();
return data;
} catch (error) {
// Timeouts if the request takes
// longer than 6 seconds
console.log(error.name === "AbortError");
}
}

Await is not as i expected in if else statements [duplicate]

This question already has answers here:
Using async/await with a forEach loop
(33 answers)
Closed 10 months ago.
let metadata = [];
allNFTs.map(async (e) => {
if (e.metadata) {
metadata.push(JSON.parse(e.metadata).attributes);
} else {
let config = {
method: "get",
url: `http://localhost:3000/api/fetch`,
header: {
"Content-Type": "application/json",
},
};
const res = await axios(config);
const attr = res.data.attributes;
metadata.push(attr);
console.log(metadata); // this one worked after below
}
});
console.log(metadata); // this one worked before above
But i want to wait till my axios done fetching, so i can finally console.log that my actual metadata.
Make an array of promises, and then await them with Promise.all
const metadataPromises = allNFTs.map((e) => {
if (e.metadata) {
return Promise.resolve(JSON.parse(e.metadata).attributes);
} else {
let config = {
method: "get",
url: `http://localhost:3000/api/fetch`,
header: {
"Content-Type": "application/json",
},
};
return axios(config).then((res) => res.data.attributes);
}
});
// await still has to be in an async function
const metadata = await Promise.all(metadataPromises);
console.log(metadata);
// or use .then
Promise.all(metadataPromises).then((metadata) => console.log(metadata));
The issue with you code, that you don't wait. The latest console.log is execurted before the map iterating all the items.
You should use somehting like that: https://www.npmjs.com/package/modern-async
E.g.
async function init() {
var ma= require('modern-async')
await ma.mapSeries(allNFTs,async (e)=>{
if (e.metadata) {
metadata.push(JSON.parse(e.metadata).attributes);
} else {
let config = {
method: "get",
url: `http://localhost:3000/api/fetch`,
header: {
"Content-Type": "application/json",
},
};
const res = await axios(config);
const attr = res.data.attributes;
metadata.push(attr);
console.log(metadata);
}
})
console.log(metadata);
}

callback function call before calling another function

I have a function which calling one API:
const response = fetch(APIfunctonName, {
method: "POST",
body: JSON.stringify(searchRequest),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((res) => res.json())
.then(
(result) => {
let urlParams = this.getRequests();
let reqid = urlParams["requested"];
var newUrl = window.location.href
.replace(`requestID=${reqid}`, "requestID=0")
.replace("requestID=0", "requestID=" + result.RequestId); //result.RequestId always have proper one
history.pushState({}, null, newUrl);
this.getList(result.RequestId); //sometimes this goes as undefined
},
(error) => {
console.log(error);
}
);
I always get proper requested in the result object, but I don't understand why sometimes I get an old Id in the getList function
You could use a Promise as follows so that you make sure the proper request is going to be passed to next instruction :
let p = new Promise((resolve , reject) => {
let urlParams = this.getRequests();
let reqid = urlParams["requested"];
var newUrl = window.location.href
.replace(`requestID=${reqid}`, "requestID=0")
.replace("requestID=0", "requestID=" + result.RequestId);
history.pushState({}, null, newUrl);
resolve(result);
});
p.then((result) => {
this.getList(result.RequestId);
});
i think the reason is the defference between sync ajax and async ajax.
if this below ajax this.getRequests() is async. Your code will get some accidental error.
let urlParams = this.getRequests();
First solution is change async to sync.
Your can change this this.getRequests() to sync. Your code will work just fine.
Second solution is use await and async.
const response = fetch(APIfunctonName, {
method: "POST",
body: JSON.stringify(searchRequest),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((res) => res.json())
.then(
async (result) => {
let urlParams = await this.getRequests();
let reqid = urlParams["requested"];
var newUrl = window.location.href
.replace(`requestID=${reqid}`, "requestID=0")
.replace("requestID=0", "requestID=" + result.RequestId); //result.RequestId always have proper one
history.pushState({}, null, newUrl);
this.getList(result.RequestId); //sometimes this goes as undefined
},
(error) => {
console.log(error);
}
);

Zapier You did not define output error when return and call included

When testing my Run Javascript action, I receive the following error
string: You did not define `output`! Try `output = {id: 1, hello:
await Promise.resolve("world")};`
I don't understand why this is happening when my function includes a return and my code calls that function.
const updateAccount = async function(z, bundle) {
const data = [{
"accountId": inputData.accountId,
"values": {
"Became Customer": inputData.becameCustomer,
"Total MRR": inputData.totalMRR,
"Company Owner": inputData.companyOwner
}
}];
const promise = await fetch("https://app.pendo.io/api/v1/metadata/account/custom/value", {
method: "POST",
body: JSON.stringify(data),
headers: {
"content-type": "application/json",
"x-pendo-integration-key": "<my integration key>"}
});
return promise.then((response) => {
if (response.status != 200) {
throw new Error(`Unexpected status code ${response.status}`);
} else {
return response;
}
});
}
updateAccount()
Though your updateAccount() function correctly waits for the request to finish in itself, there's nothing to tell the Code by Zapier function to wait for updateAccount() to finish.
You also don't have to write a function at all here - the "Run Javascript" action in Code by Zapier already wraps your code in in an async function. Try the following:
const data = [
{
accountId: inputData.accountId,
values: {
"Became Customer": inputData.becameCustomer,
"Total MRR": inputData.totalMRR,
"Company Owner": inputData.companyOwner,
},
},
];
const response = await fetch(
"https://app.pendo.io/api/v1/metadata/account/custom/value",
{
method: "POST",
body: JSON.stringify(data),
headers: {
"content-type": "application/json",
"x-pendo-integration-key": "<my integration key>",
},
}
);
if (response.status !== 200) {
throw new Error(`Unexpected status code ${response.status}`);
} else {
return response;
}

How do I pass the response of one API as a request param in another API using Request-Promise

I want to pass the response received from one API as a request parameter in another API using Request-Promise NodeJs module. Can someone pls help me in this? I am giving a brief of the sample code below:
var Sequence = {
test1: function (param) {
return request({
"method": "POST",
"uri": baseURL+"/v1/" + userID + "/test/info/",
"json": true,
"headers": {
"Accept": "application/json",
},
}).then(function (result) {
return result.pairingInfo // I want to use this pairinfInfo param in another request
})
test2 : function (param) {
return request({
"method": "POST",
"uri": baseURL+"/v1/passenger/" + userID + "/test/test/",
"json": true,
"headers": {
"Accept": "application/json",
},
"qs": {
**"pairingInfo": pairingInfo**,//This pairingInfo would come from the returned result.pairingInfo of test 1 API call
}
})
}
},
How can I achieve this?
You can use this because you have a return statement in the test1() method. So, just trigger it to get it:
"qs": {
"pairingInfo": this.test1(),
}
Sequence.test1(param)
.then(function(pairingInfo) {
Sequence.test2(pairingInfo) ;
});
// You are returning the paringInfo with the first promise, so you can use it in the .then() method.
Use this function:
const sequence = async (baseURL, userID) => {
try {
let options1 = {
method: 'POST',
uri: baseURL + '/v1/' + userID + '/test/info/',
json: true,
headers: {
Accept: 'application/json'
}
};
let pairingInfo = await request(options1);
if (pairingInfo) {
let options2 = {
method: 'POST',
uri: baseURL + '/v1/passenger/' + userID + '/test/test/',
json: true,
headers: {
Accept: 'application/json'
},
qs: {
pairingInfo: pairingInfo //This pairingInfo would come from the returned result.pairingInfo of test 1 API call
}
};
await request(options2);
return true;
} else {
console.log('Request 1 failed');
return false;
}
} catch (err) {
console.error(err);
return false;
}
};

Categories

Resources