How can we re-write the same code as per Zoho deluge? - javascript

I need some help in re-formatting the JS script to Zoho Deluge script.
This API sends whatsapp template message.
I was able to parse headers but not custom parameters.
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json-patch+json',
Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1ZDE1YTlkNi05MDQ2LTQ3OGMtYTk1MS0zNTA0ZDFlMGVkOGEiLCJ1bmlxdWVfbmFtZSI6InZpbGFrc2hhbkBuaXZlc2hvbmxpbmUuY29tIiwibmFtZWlkIjoidmlsYWtzaGFuQG5pdmVzaG9ubGluZS5jb20iLCJlbWFpbCI6InZpbGFrc2hhbkBuaXZlc2hvbmxpbmUuY29tIiwiYXV0aF90aW1lIjoiMDIvMjEvMjAyMiAxNjo0MjozOSIsImRiX25hbWUiOiI3MzU0IiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiQURNSU5JU1RSQVRPUiIsImV4cCI6MjUzNDAyMzAwODAwLCJpc3MiOiJDbGFyZV9BSSIsImF1ZCI6IkNsYXJlX0FJIn0.f1eGyiKdnj9xj48e8WUnLzTD6UGmztJGu7HrKH886og'
},
body: '{"receivers":[{"customParams":[{"name":"1","value":"Missed"},{"name":"2","value":"IVR"},{"name":"3","value":"09910076952"},{"name":"4","value":"MFP1320"},{}],"whatsappNumber":"919910076952"}],"template_name":"ivr_lead","broadcast_name":"sample"}'
};
fetch('https://live-server-7354.wati.io/api/v1/sendTemplateMessages', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));

According to your questions, you want to do POST URL using deluge script.
Based on your current data, the script to call post url is here;
url_post = "https://live-server-7354.wati.io/api/v1/sendTemplateMessages";
content_type = "application/json-patch+json";
authorization = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1ZDE1YTlkNi05MDQ2LTQ3OGMtYTk1MS0zNTA0ZDFlMGVkOGEiLCJ1bmlxdWVfbmFtZSI6InZpbGFrc2hhbkBuaXZlc2hvbmxpbmUuY29tIiwibmFtZWlkIjoidmlsYWtzaGFuQG5pdmVzaG9ubGluZS5jb20iLCJlbWFpbCI6InZpbGFrc2hhbkBuaXZlc2hvbmxpbmUuY29tIiwiYXV0aF90aW1lIjoiMDIvMjEvMjAyMiAxNjo0MjozOSIsImRiX25hbWUiOiI3MzU0IiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiQURNSU5JU1RSQVRPUiIsImV4cCI6MjUzNDAyMzAwODAwLCJpc3MiOiJDbGFyZV9BSSIsImF1ZCI6IkNsYXJlX0FJIn0.f1eGyiKdnj9xj48e8WUnLzTD6UGmztJGu7HrKH886og";
parameters_value = '{"receivers":[{"customParams":[{"name":"1","value":"Missed"},{"name":"2","value":"IVR"},{"name":"3","value":"09910076952"},{"name":"4","value":"MFP1320"},{}],"whatsappNumber":"919910076952"}],"template_name":"ivr_lead","broadcast_name":"sample"}';
parameters_value_map = parameters_value.toJSONList().toMap();
headers_value = Map();
headers_value.put("Content-Type",content_type);
headers_value.put("Authorization",authorization);
response_data = invokeUrl
[
url: url_post
type: POST
headers: headers_value
parameters:parameters_value_map
];
info response_data;
Please refer to this article for much details https://www.zoho.com/deluge/help/webhook/invokeurl-api-task.html
Thanks,
Von

Related

`POST` request to script page

The function below is contained in the Apps Script code.gs file:
function doPost(e) {
if(typeof e !== 'undefined')
return ContentService.createTextOutput(JSON.stringify(e.parameter));
}
If I make a request using fetch from the background.js of my Chrome extension and include the id parameter in the URL, I get the expected result.
const url = 'https://script.google.com/.../exec?id=123';
fetch(url)
.then(response => response.text())
.then(data => { console.log(data) }) // {"id":"123"}
Instead of writing id as a parameter in the URL, I would like to make the request using the POST method.
I tried to use the object below, but I don't know how to include the variable I want to send:
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: {}
}
I believe your goal is as follows.
You want to send the value of id=123 with the request body instead of the query parameter.
In this case, how about the following modification?
Google Apps Script side:
function doPost(e) {
if (typeof e !== 'undefined') {
const value = JSON.parse(e.postData.contents); // This is the value from the request body.
return ContentService.createTextOutput(JSON.stringify(value));
}
}
Javascript side:
const url = "https://script.google.com/macros/s/###/exec";
const data = { id: 123 };
fetch(url, { method: "POST", body: JSON.stringify(data) })
.then((res) => res.text())
.then((res) => console.log(res));
By this modification, you can see the value of {"id":123} in the console.
Note:
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script (Author: me)
To include the data you want to send in the request body and to make a POST request using the fetch function, you can do the following:
const data = {id: '123'};
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => { console.log(data) })
This send a POST request to the URL with data in the request body. The server-side function (in this case, doPost) will receive the data in the e.parameter object.
I hope this helps you.

How to add path variables to fetch api in Javascript?

Im using mockapi for a very simple project. In order to change data, i have to send PUT request. I can send the request using PostMan like in the pictures below. And everything works perfect. But i don't know where to add path variables in fetch api using Javascript. I know how to add body and i know how to add headers but i cannot figure out where to add path variables.
My code is:
async function getData() {
let url = "https://blablabla/moves/:id";
const fetchData = {
method: "PUT",
body: {
roomid: 2512,
move: "move 2",
id: 2,
},
headers: new Headers({
"Content-Type": "application/json; charset=UTF-8",
}),
};
await fetch(url, fetchData)
.then((response) => response.json())
.then((data) => console.log(data));
}
And the Postman Screenshot:
Postman Screenshot
I added the key: id part. All i want to know is that how can i add the "value: 2" part (that you can see in the picture) to fetch api. Any help will be appreciated.
I tried to fetch PUT request in javascript but couldn't figure out where to put Path Variables.
There are no path variables in the fetch api, but you can pass the id in the string itself like so:
async function getData(id) {
let url = `https://blablabla/moves/${id}`; // use string interpolation here
const fetchData = {
method: "PUT",
body: {
roomid: 2512,
move: "move 2",
id: 2,
},
headers: new Headers({
"Content-Type": "application/json; charset=UTF-8",
}),
};
await fetch(url, fetchData)
.then((response) => response.json())
.then((data) => console.log(data));
}

How authorise a Fetch call with Authorisation Token?

I am trying to call a Freesound API. Fetch throws an Unauthorised error whereas Postman works.
Code
const BASE_URL = "https://freesound.org/apiv2/sounds/";
const rain = "58835";
const APIKEY = "foo";
const headers = {
method: "GET",
headers: {
'Authorization': `Token ${APIKEY}`,
},
mode: "no-cors",
};
fetch(BASE_URL + rain, headers)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(err));
First of all, you should never post API Key on any public platform as anyone can access and exploit the API that you would have paid for.
Solution
The endpoint you're using seems to be invalid. Also, don't use mode: 'no-cors' unless an opaque request serves your need. Else, you won't be able to access any property in the response object.
Reason of 401 error: Using no-cors prevents Authorization header to be added in your request.
Getting past CORS error: It usually happens in localhost during development. You can use an extension which would allow CORS.
const QUERY = 'piano';
const API_KEY = 'foo';
const BASE_URL = `https://freesound.org/apiv2/search/text/?query=${QUERY}`
const headers = {
method: 'GET',
headers: {
Authorization: `Token ${API_KEY}`,
}
};
fetch(BASE_URL, headers)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(err));

Issues with passing all values entered on a form, via formData, with fetch API

Why formData goes empty to my express+mongodb server? I've some problems with querySelector and addEventListener, but for now thats ok. However, I don't find a way for sending all values of my form to the server. Please, someone help me?
document.querySelector('#enviar-
cadastro').addEventListener('click', Cadastrar);
Cadastrar('http://localhost:5000/usuario/novo')
.then(response => console.log(response.json()))
.then(data => console.log(data))
.catch(error => console.log(error));
function Cadastrar(url) {
const formDados = new FormData(document.querySelector('#signup'))
return fetch(url, {
method: 'POST',
body: JSON.stringify(formDados),
headers: {
"Content-Type": "application/json"
}
})
};
First of all console.log(formDados) inside Cadastrar and see what you get.
This should also help: https://code.lengstorf.com/get-form-values-as-json/

React Native - Fetch POST not working

I am having huge troubles getting my fetch POST calls to work on iOS. My standard Fetch calls work and the Fetch POST calls work fine on android but not iOS.
The error that comes up is "Possible Unhandled Promise Rejection (id: 0): Unexpected token < in JSON at position 0"
It actually saves the post data to my server but throws that error.
I tried debugging the network request using GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; before the API call coupled with using CORS in my chrome debug tools. From there I can see that it is making two post calls one after the other. The first one has type "OPTIONS" while the second one has type "POST". It should probably be noted that the call works in the App while using CORS and the line of code above.
I'm very confused and have exhausted all avenues.
My code im using for refrence is as follows.
return fetch(url,{
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then((res) => res.json());
If JSON.stringify is not working, then try to use FormData.
import FormData from 'FormData';
var formData = new FormData();
formData.append('key1', 'value');
formData.append('key2', 'value');
let postData = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
}
fetch(api_url, postData)
.then((response) => response.json())
.then((responseJson) => { console.log('response:', responseJson); })
.catch((error) => { console.error(error); });
You use the following code for POST request in react native easily. You need to only
replace the parameter name and value and your URL only.
var details = {
'userName': 'test#gmail.com',
'password': 'Password!',
'grant_type': 'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('http://identity.azurewebsites.net' + '/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}).
.then((response) => response.json())
.then((responseData) => {
console.log("Response:",responseData);
}).catch((error) => {
Alert.alert('problem while adding data');
})
.done();
I would guess the response you are receiving is in HTML. Try:
console.warn(xhr.responseText)
Then look at the response.
Also, IOS requires HTTPS.
Edit: Possible duplicate: "SyntaxError: Unexpected token < in JSON at position 0" in React App
Here is an example with date that works for me!
The trick was the "=" equal and "&" sign and has to be in a string format in the body object.
Find a way to create that string and pass it to the body.
====================================
fetch('/auth/newdate/', {
method: 'POST',
mode: 'cors',
redirect: 'follow',
body: "start="+start.toLocaleString()+"&end="+end.toLocaleString()+"",
headers: new Headers({
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
})
}).then(function(response) {
/* handle response */
if(response.ok) {
response.json().then(function(json) {
let releasedate = json;
//sucess do something with places
console.log(releasedate);
});
} else {
console.log('Network failed with response ' + response.status + ': ' + response.statusText);
}
}).catch(function(resp){ console.log(resp) });
server node.js?
npm i cors --save
var cors = require('cors');
app.use(cors());
res.header("Access-Control-Allow-Origin: *");

Categories

Resources