Unable to authenticate rest call through XMLHttpRequest - javascript

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)?

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.

Using the Pivotal API in 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
}

XMLHttpRequest javascript POST-request issue "cannot load url"

var http = {};
http.request = (function () {
function send(jsonObject, url) {
var jsonString = JSON.stringify(jsonObject);
var req = new XMLHttpRequest();
req.open("POST", url);
req.setRequestHeader("Content-Type", "application/json");
req.send(jsonString);
}
return {
send: send
};
})();
I am trying to use this javascript function to send data. However it gives me an error:
"XMLHttpRequest cannot load url. Response for preflight is invalid (redirect)"
What am i doing wrong?
Since you are setting the content-type to be json, this is considered a preflighted request. What this means is that essentially two requests are being made: the first one asks the server permission to make a request, and the second one is the actual request. For such cases, you need to at least check for origin of the request on your server side:
header('Access-Control-Allow-Origin: your origin url')
You might also have to check the request method:
header('Access-Control-Allow-Methods: POST')

Categories