`POST` request to script page - javascript

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.

Related

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

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

ReactJS - unable to fetch from API

So what I am trying to do is do send some data by clicking a submit button (A mathematical expression) to a Django-API. There this expression is processed and a new expression is returned to another textbox. I am trying to do this in a single function. The Post requests are working perfectly fine which I have checked through the Postman application.
I am unable to fetch the processed data from the API. I am getting the following error -->
GET http://127.0.0.1:8000/differentiate/ 405 (Method Not Allowed)
The overview of the application -->
The code for my function is ->
async postData() {
const url = 'http://127.0.0.1:8000/differentiate/';
let result = await fetch(url,{
method: 'post',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
functiondata: this.fx
})
});
fetch(url).then(res => res.json()).then(json => {
this.setState({
fprimex: JSON.stringify(json)
})
})
};

POST and GET API Request using fetch, cannot get the data

i'm trying to use this website: https://rel.ink/,
to implement a link-shortener in my webapp,
i can successfully POST a request, but what i GET back is the same object, not a shortened version.
I know it's basic stuff but i can't wrap my head around it.
The website states that i need to send more information with my GET request, but the GET requests should not contain a body yes?
Here's my code:
async function fetchNewLink() {
let newLinkJson = await postLink(input.value)
let newLink = await getShortLink(newLinkJson)
console.log(newLink)
}
function postLink(input) {
return fetch('https://rel.ink/api/links/', {
method: 'POST',
body: JSON.stringify({
url: input
}),
headers: {
"Content-type": "application/json"
}
})
.then(response => response.json())
.then(json => json)
}
function getShortLink(response) {
return fetch('https://rel.ink/api/links/' + response.hashid)
.then(result => result.json())
.then(newLink => newLink)
}
Many thanks
If what you're trying to get is the shortened version of the link, the API does not return exactly that when you make a request. However, all you need is the hashid it returns. The shortened link is the main website's url(https://rel.ink) concatenated with the hashid.
So if the API returns nJzb3n as the hashid when you make a POST request, the shortened link would be https://rel.ink/nJzb3n
I hope that helps.

Is there an equivalent of `curl -v` in javascript fetch API?

How can I view the request that Javascript fetch sends to the server when I do something like this:
var h = new Headers({
"X-API-Key": KEY,
});
var obj;
fetch(url, {
headers: {h}
}).then(response => response.json())
.then(data => {
obj = data;
})
.then(() => {
console.log(obj);
});
similar to the output given by curl -v?
Thanks
Edit: I am using React Native.
To be more clear, what I am asking is that I know under the hood fetch is creating and using a Request object, is there a way to print the generated object. I am aware that I can create my own request object and pass that to fetch instead of a url but that is not what I want to do.

Add parameters to post request using js on client side

I'm developing a "TODO" app using node.js and mongodb.
I'm trying to post a new task from the client but I didn't success to pass parameters to the server and from there to the database.
Client code:
<script>
function addData(item, url) {
var text = document.getElementById("myTask").value;
return fetch('/todos',{
method: 'post',
body: text
}).then(response => response.json())
.then(data => console.log(data));
}
</script>
Server code:
app.post('/todos',(req,res) =>{
console.log("\n\n req.body is: \n\n",req.body);
var todo = new Todo({
text: req.body.text});
todo.save().then((doc) =>{
res.send(doc);
console.log(JSON.stringify(doc,undefined,2));
},(err) =>{
res.status(400).send(err); //400 = unable to connect
console.log("Unable to save todo.\n\n\n" , err);
});
});
And the problem is that the client doesn't send the body to the server,
and the body is null on the server side:
See the logs here
(as you can see: req.body = {})
In the js code, I tried to pass the body parameter but I guess I did something wrong so I want to know the best way to pass parameters back to the server (not only the body but text, time and etc)
Thank in advance,
Sagiv
I think that you are missing something. Try to use name of param
body: JSON.stringify({data: text})
OR
read here Fetch: POST json data
I used this code:
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await rawResponse.json();
console.log(content);
})();
and now I succeeded to pass data to the request.
Thanks everybody

Categories

Resources