This JavaScript Fetch code returns the data I need in Postman. But, I am trying to get this code to work in Google Script Editor for my google sheet, and it is giving me the following error:
ReferenceError: Headers is not defined line 3.
I am brand new to coding, so please bear with me.
Any idea what's wrong here?
POSTMAN CODE:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
var raw = "{\n \"id\": 1,\n \"jsonrpc\": \"1.0\",\n \"method\": \"getbeaconbeststatedetail\",\n \"params\": []\n}";
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://mainnet.incognito.org/fullnode", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
EDIT:
I have tried to update this:
function myFunction() {
var data = {
'request': {
'id': '1',
'jsonrpc': '1.0',
'method': 'getbeaconbeststatedetail',
'params': []
}
};
var payload = JSON.stringify(data);
var options = {
'method' : 'GET',
'headers': { 'Content-Type': "text/plain", 'Accept': "text/plain"},
'muteHttpExceptions': true,
'contentType' : 'application/json',
'body' : payload
};
var url = "https://mainnet.incognito.org/fullnode";
var response = UrlFetchApp.fetch(url, options);
var txt= response.getContentText();
var d=JSON.parse(txt);
var sh1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet14");
for (let i = 0; i < d.length; i++) {
sh1.getRange(1, 1).setValue(d);
}
}
But, I am still getting the following error:
Exception: Request failed for https://mainnet.incognito.org returned code 400
If you are trying to make an HTTP request from Google Apps Script, you have to use the UrlFetchApp()
method.
As @Tanaike points out, GAS is based in JS but not all JS functions are allowed. However GAS does have many services to integrate with G Suite products, and external APIs or services. One very useful service is URL Fetch Service which allows you to perform any type of Http request.
// Make a GET request with headers.
var options = {
"method" : "GET",
"headers" : {
"Content-Type" : "text/plain",
"API_KEY": "dummydummy"
}
};
var response = UrlFetchApp.fetch("https://api.myawesomeapi.com/get", options);
You can also make POST or other requests. Please refer to the examples in the documentation for use cases.
You are receiving the 400 "Bad request" error from the "fullnode" endpoint because it requires a POST request with a payload.
function fetchFullNode() {
var url = "https://mainnet.incognito.org/fullnode";
var data = {
"jsonrpc":"1.0",
"method":"getblockchaininfo",
"params":"",
"id":65
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch(url, options);
var txt= response.getContentText();
return JSON.parse(txt);
}