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

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;
}

Related

Return full data on JavaScript Promise for a function within a class while using node-client-ntlm

I have a function within a class that makes a call and returns a promise object with data. I do get the data back the issue is I cannot figure out how to make the call wait till all of the data is returned at the moment it only returns a few lines of data and cuts off the rest of the return.
async callCurl(postFields) {
this.postFields = postFields;
const response = await client
.request(
{
url: this.url,
method: "POST",
debug: true,
body: "folderGuid=" + this.postFields,
headers: {
"content-type": "application/x-www-form-urlencoded",
},
resolve: true,
},
"username",
"password",
"",
"domain"
)
.then((response) => {
console.log(response.body);
})
.catch(function (error) {
console.log(error);
});
//return response;
}

Unable to access response.status with React from a custom rails API

I am trying to get the status of a request I do from a React website I am working on, using axios to fetch make requests to a RoR API I developed. I would like to confirm that the POST request succeeded by accessing the status value from this (which is the output of a console.log(response):
Promise { <state>: "pending" }​
<state>: "fulfilled"​
<value>: Object { data: {…}, status: 201, statusText: "Created", … }​​
config: Object { url: "pathname", method: "post", data: "{\"user\":{\"email\":\"lou10#email.com\",\"username\":\"lou10\",\"password\":\"azerty\"}}", … }​​
data: Object { data: {…} }​​
headers: Object { "cache-control": "max-age=0, private, must-revalidate", "content-type": "application/json; charset=utf-8" }​​
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 201
statusText: "Created"​​
<prototype>: Object { … }
index.jsx:51:11
But when I try a console.log(response.status) all I get is an undefined.
Here is the code :
import axios from 'axios';
import { BASE_URL } from "./config.js";
const post = async (
endpoint,
body = null,
jwt_token = null,
header = { "Content-Type": "application/json" }) => {
let opt = header;
if (jwt_token){
opt["Authorization"] = jwt_token
}
try {
const response = await axios.post(BASE_URL + endpoint, body, { headers: opt })
return response
} catch (err) {
console.error(`An error occurred while trying to fetch ${endpoint}. ${err}`);
}
}
export default post;
const handleSignup = async ({ email, username, pwd }) => {
let body = {
user: {
email: email,
username: username,
password: pwd
}
};
return await post("/users", body);
};
useEffect(() => {
if (passwordCheck === false) {
console.log("Passwords do not match");
} else if (passwordCheck === true && userData) {
const response = await handleSignup(userData);
console.log(response.status);
// history.push({ pathname: "/", state: response.status });
}
}, [passwordCheck, userData]);
I am thinking to change the response from my API, but I really doubt it is the right approach.
Edit 1: adding some complementary code
you have to declare the function you give in parameter to useEffect as async to be able to use await inside for your async function handleSignup
useEffect(async () => {
if (passwordCheck === false) {
console.log("Passwords do not match");
} else if (passwordCheck === true && userData) {
const response = await handleSignup(userData);
console.log(response.status);
// history.push({ pathname: "/", state: response.status });
}
}, [passwordCheck, userData]);

How can I RETURN Axios error to client? (not only logging)

I know this has been asked many times but what I am facing is a really annoying problem.
I have my server which returns error string with status code 500. When i use axios and catch the error, i can log it easily, but when i return it, i can try everything but its gives me undefined, or it doesn't append anything.
export const submitCheckout = async (betImport, ticket_id, token) => {
const res = await axios({
method: "post",
url: rootUrl + "bets/checkout/" + ticket_id,
headers: {
"x-auth-token": token,
},
data: {
betImport,
},
}).catch(({ response }) => {
console.log(response.status) //this works
return response;
});
return res.data;
};
//HERE I CALL THE FUNCTION
const res = await submitCheckout(sum, ticket_id, token);
//here i can access only the body of the error, even if i try to append something to it.
if (res.ticket_id) {
emptyTicket();
setmodal({
show: true,
title: "SUCCESS",
subtitle: "BET PLACED",
maxwin: `${res.maxWin}`,
ticketId: `${res.ticket_id}`,
account_sum: `${res.account_sum}`,
});
ModifyAccountUser(user, res.account_sum);
} else {
setmodal({
title: "ERROR",
show: true,
status: `${res.status}`,
error: `${res}`,
});
if (res.toString().includes("Token")) history.push("/login");
}
//WHAT I WANT TO DO
export const submitCheckout = async (betImport, ticket_id, token) => {
const res = await axios({
method: "post",
url: rootUrl + "bets/checkout/" + ticket_id,
headers: {
"x-auth-token": token,
},
data: {
betImport,
},
}).catch(({ response }) => {
return {...response, response.status}; //this returns the body only,
return {res: response, status: response.status}; //this crashes,
return response + "-"+ response.status}; //this was my desperation attack and failed as well
});
return res.data;
};
Throw an error and put your response inside it as a string. Then access it in your promise with error.message:
async function foo(){
try{
const res = await ax.post("url", {params})
return res
}
catch(err){
throw new Error("my error message")
}
}
//then
foo()
.then(res=> do stuff)
.catch(err=> err.message)
You can try this.
try {
let res = await Axios({
method: {method},
URL: {url},
data: {body}
});
let data = res.data;
return data;
} catch (error) {
console.log(error.response); // this is the main part. Use the response property from the error object
return error.response;
}

TypeError Failed to fetch in React

async handleSubmit(event) {
event.preventDefault();
console.log("test");
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
val1: "val1",
val2: 2
})
};
const response = await fetch(
myURL,
requestOptions
);
if (response.status >= 200 && response.status <= 299) {
const jsonResponse = await response.json();
console.log(jsonResponse);
} else {
console.log(response.status, response.statusText);
}
}
I wrote this handleSubmit function for a form that needs to send an API request and get back some data. However, it gives the error Typeerror failed to fetch every time with no further explanation or messages. I tried error handling but still no output at all from the fetch part. What could be the reason?

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