Module of the Headers Class/Javascript/ - javascript

I'm not a technical person, so I can't code or anything, but I have to incorporate this API into google sheets.
Therefore I use this Javascript Code Sample in google Appscript. But There is no definition of the Headers.
var myHeaders = new Headers();
myHeaders.append("x-access-token", "<my gold api key>");
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://www.goldapi.io/api/XAU/EUR", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Can somebody tell me where I can find the Modul of the Headers Class and install it? Or is there another way to incorporate this API into google sheets?
Thank you for your Help!

Add these two lines at the top:
const fetch = require('node-fetch');
const { Headers } = fetch;
This is for Node-js. In a browser context your code would work without this, as the fetch API is included out of the box, and also Headers is defined.

Related

SharePoint cannot get Access Token with JavaScript?

I need to get access token from SharePoint, In order to upload some files!
I got access token from postman successfully, But when I try to do the same request with Javascript!
const generateToken = async () => {
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
var formdata = {};
formdata["grant_type"] = "client_credentials";
formdata["client_id"] = "<client_id>";
formdata["client_secret"] = "<client_secret>";
formdata["resource"] =
"00000003-0000-0ff1-ce00-000000000000/site_url#tenant_id";
const body = Object.keys(formdata)
.map((key) => `${key}=${formdata[key]}`)
.join("&");
var requestOptions = {
method: "POST",
headers,
body,
};
await fetch(
"https://accounts.accesscontrol.windows.net/<tenant_id>/tokens/OAuth/2",
requestOptions
)
.then((response) => response.json())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
};
generateToken();
when I execute the page which have this script I got this error
error TypeError: Failed to fetch
at generateToken
But IDK why the respose status is 200 OK, without returning body which contain access_token
Any help is much appreciated!
You cannot get the token from javascript like that, only from single page applications because of the security issues: you expose your client secret.
You can use Microsoft Authentication Library (MSAL) for JS instead.

How to correctly consume a rest service created with Genexus?

I have been trying to consume a simple web service crated with GeneXus, it should receive a "nPais" variable (integer) and respond an object with the text property based on the given number. It just doesn't work. I have confirm that the service work by testing it with soapUI (adding the WSDL), but when trying to consume it with postman it responds the correct structure, but with the text property empty.
This is my source tab from the WS.
&sdtServicio = New()
&Servicio.SetEmpty()
Do Case
Case &nPais = 1
&sdtServicio.Texto = "Hola México"
Case &nPais = 2
&sdtServicio.Texto = "Hola Argentina"
Otherwise
&sdtServicio.Texto = "HOLA MUNDO"
Endcase
This is on rules tab
Parm(in:&nPais, out:&sdtServicio);
And here is how I have been trying to consume the service on JS.
function getGreeting(value) {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Cookie", "GX_CLIENT_ID=54f383cc-0719-444d-a252-c8799c1202a0");
var raw = JSON.stringify({
"nPais": 1
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://localhost:8080/PotentorDesaPotDesa/rest/WSHolaMundo", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
This is the response I get.
{"sdtServicio":{"Texto":""}}
The trick was only to change the protocol from SOAP to internal on the properties of my object.

imgur api image uploading cross origin resource sharing error

hope you all doing fine,
currently i am working on a small html static project and i have image uploading there so i used imgur api, i tested it out on postman it seems pretty okay, but when i try to code it like that
var myHeaders = new Headers();
myHeaders.append("Authorization", "Client-ID ******");
myHeaders.append("Access-Control-Allow-Origin", "*");
var formdata = new FormData();
formdata.append("image", image);
var requestOptions = {
method: "POST",
headers: myHeaders,
body: formdata,
redirect: "follow",
};
fetch("https://api.imgur.com/3/upload", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
i only got this error
cross origin resource sharing error header disallowed preflight response
am i doing something wrong here

ReferenceError: Headers is not defined in Google scripts

I am trying to automate between reply.io and Gsheets, to automatically do API calls, so I can create a 'live' dashboard in Google Sheets through script editor.
I am using the documentation on their website (https://apidocs.reply.io/#b24cfec9-3e95-4409-b520-8dfecd75e682). I only work with Python and I succeed there, but somehow I can't seem to make it work in JavaScript.
The script I use is:
function myFunction() {
var myHeaders = new Headers();
myHeaders.append("x-api-key", "{{Your_apiKey}}");
var raw = "";
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://api.reply.io/v2/schedules/default", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
The error I am getting is:
ReferenceError: Headers is not defined
myFunction # Code.gs:2
Google Apps Script do not use the browser built ins, instead they have their own builtins. In this case you would need to use UrlFetchApp.
function myFunction() {
let myHeaders = {
"x-api-key": "{{Your_apiKey}}"
};
let params = {
method: 'get',
headers: myHeaders,
followRedirects : true,
};
let response = UrlFetchApp.fetch("https://api.reply.io/v2/schedules/default", params);
Logger.log(response.getContentText());
}

Network error with Reed API fetch request & basic auth

I am trying to make a request to the REED jobs API although I am getting the error: TypeError: NetworkError when attempting to fetch resource. The call is being made in a React component. The Reed API states You will need to include your api key for all requests in a basic authentication http header as the username, leaving the password empty. This is the part that confuses me and I do not know how to configure the fetch in this way. To help with this, I have sent the API call from Postman and have managed to get response successfully. Because of this, I used the code generation function of Postman to make the below call, but it does not work:
var myHeaders = new Headers();
myHeaders.append("Authorization", `${process.env.REACT_APP_REED_KEY}==`);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
Update:
I have changed the code to the below. Unfortunately, I am still getting an error. I am also now getting a new error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15. (Reason: CORS preflight response did not succeed).
Updated code:
import { encode } from "base-64";
var myHeaders = new Headers();
myHeaders.append("Authorization", `Basic ${encode(process.env.REACT_APP_REED_KEY)}`);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));

Categories