Question

Form Encoded Fetch inside Code App (Javascript)

  • 17 December 2023
  • 1 reply
  • 55 views

Badge

 Hi there -

I sometimes will use Code rather than Webhooks to send requests if I need to do some sort of handing on the back end with the data or potential errors. I’ve never had an issue setting up simple requests but I’ve never had to send the data as form data and I keep getting a 400 - Bad Request back even though this request, as written, will work just fine in other js environments. It’s gotta be something I just don’t know or understand about how something needs to be formatted to work inside Zapier. For the example, I just wrote in the inputs rather than passing them in as inputData for simplicity - Anyone have any ideas why this won’t work?

await main();

async function main() {

let email = 'testing@email.com';
let password = 'randompasswordstring';
let subscription_id = 1;
let first_name = 'John';
let last_name = 'Doe';
let bdid = 'serviceapikey';

const bodyData = new URLSearchParams();
bodyData.append('email', email);
bodyData.append('password', password);
bodyData.append('subscription_id', '1');
bodyData.append('first_name', first_name);
bodyData.append('last_name', last_name);

let createUser = await createBDUser(bodyData, bdid);
console.log(createUser);

// output = {id: 1}; - included arbitrarily for testing as the Code app requires it.

};

async function createBDUser(bodyData, apikey)
{
let endpoint_url = `https://endpoint.targetservice.com/v2/users/create`;

const postBDUser = async (user) => {

const options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Api-Key': apikey
},
body: bodyData
};
const response = await fetch(endpoint_url, options);
return response;
};

let bdResult = await postBDUser();
return bdResult;
};

 


This post has been closed for comments. Please create a new post if you need help or have a question about this topic.

1 reply

Userlevel 7
Badge +14

Hi @Alchemick 

Help articles and examples for using the Code app:

https://zapier.com/apps/code/help

 

You can also try generating the code with the help of the AI feature in the Code step.

https://help.zapier.com/hc/en-us/articles/15666688064013-Generate-a-Code-step-using-AI-Beta-

 

Another option is to use ChatGPT to generate/debug the Code.