How to add path variables to fetch api in Javascript? - 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));
}

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.

Why can't I send a form data from axios?

I am consuming an api that asks me to send a filter series within a formData, when doing the tests from Postman everything works without problem, I tried with other libraries and it also works without problem, but when trying to do it from axios the information does not return with the filters.
This is the code I am using:
const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');
let config = {
method: 'get',
url: 'https://thisismyurl/filter',
headers: {
'Authorization': 'JWT MYTOKEN',
...data.getHeaders()
},
data : data
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
You can send Form-data using get method, but the most servers, will reject the form data.
However it is not recommended anymore. The reason is, first because it is visible in the URL and browsers can cache them in it’s history backstacks, and second reason is because browsers have some limitations over the maximum number of characters in url.
If you are to send only few fields/input in the forms you can use it but if you have multiple inputs you should avoid it and use POST instead.
At the end it depends on your own usecase. Technically both GET and POST are fine to send data to server.
replace get with post
const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');
let config = {
method: 'post',
url: 'https://thisismyurl/filter',
headers: {
'Authorization': 'JWT MYTOKEN',
...data.getHeaders()
},
data : data
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});

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

fetch call in react app doest not return body, same call works fine with postman

I have a React app running in localhost and backend REST APIs running in localhost.
When I try to make a POST call to REST API, the call is successful. But the body in empty.
The sample code can be found below.
const body = await fetch("url", {
method : 'POST',
headers: {
"Accept" : "application/json",
"Content-Type" : "application/json"
},
body: JSON.stringify(comp)
}).then((res) => {
console.log(res);
}).then(data => console.log(data));
Call is successful.
res looks like :
returned object
Same code works fine in Postman. Also all the GET API calls work fine from the same react app.
Two problems
You don't return anything in the first then() and
You need to use res.json() promise to access the data.
try something like:
const req = await fetch("url", {
method : 'POST',
headers: {
"Accept" : "application/json",
"Content-Type" : "application/json"
},
body: JSON.stringify(comp)
});
const data = await req.json();
console.log(data)

Categories

Resources