Using the Pivotal API in javascript - javascript

I am new to using API's that have authentications, on the pivotal website they have commands using curl commands that look like this
export TOKEN='your Pivotal Tracker API token'
curl -X GET -H "X-TrackerToken: $TOKEN" "https://www.pivotaltracker.com/services/v5/projects/99"
I was wondering how I can convert this to JavaScript by making a request, the problem is I don't know where to put the token when making the request to an API.
So far in JavaScript I have this
function reqListener () {
console.log(this.responseText);
}
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://www.pivotaltracker.com/services/v5/projects/99?fields=version");
oReq.setRequestHeader(header, 'Pivotal token');
oReq.send();
Also i dont know what to in place of header.

When you set up your http request put the access token in the headers using the key "X-TrackerToken". I have been using the following headers when making a request:
{
"Content-Type": "application/json",
"X-TrackerToken": apiToken
}

Related

curl http request to node-red

I'm very very new to node-red and don't know a thing about sending a http request to node-red. I've been trying out this method to send request to node-red but it gave me status code 0.
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://my.node.com:port/endpoint", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
data: "data"
}));
console.log(xhr.status);
My senior suggested me to use the curl command - and I have no idea how to do that. I'm not used to using curl nor have time to spend to explore deeply as I have limited time available. I attempted to use this method but is returned with error msg undefined
msg.payload = "data to post";
msg.headers = {};
msg.headers['content-type'] = 'application/json';
return msg;
How can I send http request to node-red?

Can't access httpOnly (like "set-cookie") header of a response when making request from a Chrome Extension

I'm trying to make a script that will automate something for me and my goal is to make an HTTP request and grab the "set-cookie" that is in the response's headers.
I understand why it's not accessible when done from a normal web page (httpOnly and all) but I am doing it from the background script in a chrome extension.
I tried using both fetch and xhr but they both didn't show me the set-cookie header in the response.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
console.log("headers", xhr.getAllResponseHeaders()); // doesnt return httpOnly headers
}
};
xhr.open("GET", 'https://' + host, true);
xhr.send();
or
fetch('https://' + host, {method: 'GET'})
Is there any way to get permission to read those headers? Maybe I need to use something other than fetch? Any help would be greatly appreciated.

Sending a POST request from JavaScript not passing in JSON params

I am trying to call a Firebase Cloud function written in python from my website. The function works perfectly when I call it from command line using curl, however, when I try to do the same from JavaScript I am getting the following issue. Essentially the JSON params are not being received.
How I am calling in JavaScript
var xmlhttp = new XMLHttpRequest();
var theUrl = "https://us-central1-scan2checkout.cloudfunctions.net/registerUser";
xmlhttp.open("POST", theUrl,true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send('{"auth":"ac_Fn0GuKLhuh8yltMVlmFeBkQpdpaTrqug"}');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
console.log(xmlhttp.responseText);
}
}
Cloud Function
def registerUser(request):
print(request) # Printing '<Request 'http://us-central1-scan2checkout.cloudfunctions.net/' [OPTIONS]>'
print(request.json) # Printing 'NONE' :(
auth = request.json['auth'] # Issue is here
# ... SOME STUFF ...
return {...},201
How it works when I use command line
time curl -v -X POST -d '{"auth":"ac_Fn0GuKLhuh8yltMVlmFeBkQpdpaTrqug"}' -H "Content-type: application/json" https://us-central1-scan2checkout.cloudfunctions.net/registerUser
If you run this now you'll probably get something like "Authorization code expired" which is correct.
To handle this request, you will need to set the appropriate Access-Control-Allow-* headers in your Cloud Function to match the requests you want to accept. Please see an example of a CORS function written in Python.
You will notice that CORS consists of two requests: a preflight OPTIONS request, and a main request that follows it.
The preflight request contains the following headers:
Access-Control-Request-Method - indicates which method will be sent in the main request.
Access-Control-Request-Headers - indicates additional headers along with the origin of the main request.
Let me know if it helps.

How do I add a request body parameter to an API request in Javascript? [duplicate]

This question already has an answer here:
Make XmlHttpRequest POST using JSON [duplicate]
(1 answer)
Closed 3 years ago.
I am using the Spotify API and need to get an access token, although the example/guide (https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow) is written in cURL, which I need to translate to Javascript.
The main issue is setting the request body parameter "grant_type" to "client_credentials" and "The body of this POST request must contain the following parameters encoded in application/x-www-form-urlencoded as defined in the OAuth 2.0 specification:" which I'm not sure how to do.
I've tried the cURL on a command prompt and it works fine, but I will not be using cURL.
What I'm trying to do
curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token
What I have
var auth_id = "";
var getToken = new XMLHttpRequest();
getToken.open('POST', 'https://accounts.spotify.com/api/token', true);
getToken.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
getToken.setRequestHeader('grant_type', 'client_credentials'); //this param needs to be in body but how???
getToken.setRequestHeader('Authorization', 'Basic (this part is my client id but I am not including it for obvious reasons)');
getToken.onload = function (){
var data = JSON.parse(this.response);
console.log(data);
auth_id=data.access_token;
}
getToken.send("client_credentials");
I would recommend you to use a more modern fetch api like native fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API or a third party library like axios https://github.com/axios/axios
Using fetch it is fairly easy
const url = 'https://accounts.spotify.com/api/token';
const request = new Request(url, {
headers: new Headers({
Authorization: 'Basic XXX',
}),
body: JSON.stringify({
grant_type: 'client_credentials'
}),
method: 'POST',
);
const response = await fetch(request);

Unable to authenticate rest call through XMLHttpRequest

I have been using postman to test an API which, I am successfully able to call.
When I try to execute this call through javascript I get an authentication error.
The URL and authorization match that of the postman call and when I call using these details with curl I am able to retrieve the correct data.
<script type="text/javascript">
var data = new FormData();
data.append("attributeId", "");
data.append("validFrom", "");
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "http:/restpAPI/test");
xhr.setRequestHeader("authorization", "Basic asdsadsadjlafdkfjkldfj==");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "dsadasd-asdsad-asd-asd-aasd");
xhr.send(data);
</script>
When I run a local web page with this script I get a 401 saying Unauthorized.
What is the difference between the JavaScript code and postman or cURL and is there a way of authenticating from JavaScript?
Update
I have discovered that setting the RequestHeader with the authorization key turns the request from a get to an options. This is causing the error.
Although HTTP Headers are supposed to be case insensitive, have you tried setting the headers' names with title case (Authorization)?

Categories