I am trying to subscribe to a firebase cloud messaging topic with the following http post request:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://iid.googleapis.com/iid/v1/etLaB36oW1w...nyO_Zc26ZPOFTeNuf58-l6uSoJ9Xs1JRYKfqxsmKkdrR-oX4tQsuS_z5C0/rel/topics/Byfjordskole");
xhr.setRequestHeader("authorization", "key=AAAABlxTfxY:APA91bGE3sa09zq...dZSIVJul3N-y1hMJqAoKngwjC_El3rEuH4_-S2gOxKcdAF67HHhGK7pAWJrhyt8JthJGm_QN6JdXTBow62nYodgFvLncfSniwtBinBgIPLaKpT");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "a3ce72a5-f8ba-99e4-59d6-fe3295b84f6e");
xhr.send(data);
This works when I use Postman, but I get the following error message when I try to use the same code on my javascript app:
XMLHttpRequest cannot load https://iid.googleapis.com/iid/v1/eOEiRqvhD4s:APA91bFFb-uP-Xhf2iD-ALUI_X4M7…gA_YgQgmuib7cCL7UuSdlhUUWmsqwRnkcO2kpAIV_H-_xBPlPd/rel/topics/Eiganesskole.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://sk......e.top' is therefore not allowed access.
Do firebase cloud messaging inhibit me from making this types of request, or is there a solution to this problem? Any help will be highly appreciated.
This Stack Overflow answer solved my problem: https://stackoverflow.com/a/2067584/6177181
The problem was browser security related: and this kept me from making cross domain requests. The Solution was to wrap my code in script tags to avoid this restriction. So instead of doing this request from another javascript file, I simply added the request code in the index.html file like this:
<script>
function subscribe(currentToken){
"use strict"
let stored_topics = localStorage.getItem("topicsList");
let topics = JSON.parse(stored_topics);
for (let i = 0; i < topics.length; i++){
let data = null;
let xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
let body = {};
let url = "https://iid.googleapis.com/iid/v1/"+currentToken+"/rel/topics/"+topics[i];
xhr.open("POST", url);
xhr.setRequestHeader("authorization", "key=AAAABlxTfxY:....QAVfBJI8J0RdZSIVJul3N-y1hMJqAoKngwjC_El3rEuH4_-S2gOxKcdAF67HHhGK....2nYodgFvLncfSniwtBinBgIPLaKpT");
xhr.setRequestHeader("content-type", "application/json");
xhr.send(data);
}
}
</script>
(The currentToken is requested from the firebase cloud messaging API in the same file(index.html)).
Follow the instructions on this link :https://firebase.google.com/docs/cloud-messaging/js/receive for information about Firebase cloud messaging.
Related
I am trying to develop a browser extension that will help people to some stuff way easier.
One of the things that I need to do is sending couple of http requests.
I need to recreate requests that site makes when doing certain things.
Now site uses Request Payload which is my first time using(used form data),therefore I don't know how to make Request Payload same as when site sends request.
var request = new XMLHttpRequest(),
url = 'https://www.hidden.com/api/v1/tipuser/',
data = 'steam_64=76561198364912967&tip_asset_ids=[]&tip_balance=0',
token ='...';
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'text/plain');
request.setRequestHeader('authorization', token);
request.send(data);
This is my code and after sending it you can see how my Request Payload looks.
I have been having difficulties for days now and I searched online but couldn't find solution to this.I know that I just have to write it differently .
This is site's request
This is my request
Cheers!
Could you try sending your request as application/json and build your data object like in the example below?
Your Content-type request header should be application/json
var request = new XMLHttpRequest(),
url = 'https://jsonplaceholder.typicode.com/posts/',
data = {
steam_64: '76561198364912967',
tip_asset_ids: [],
tip_balance: 0,
token: '',
};
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json');
request.setRequestHeader('authorization', data.token);
request.send(JSON.stringify(data));
I'm trying to get client IP in my angular app.
I'm using this code:
$http.get("http://l2.io/ip.js").then(function(response) {
$scope.ip = response.data;
});
But it make
Error: XMLHttpRequest cannot load http://l2.io/ip.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9001' is therefore not allowed access.
How to add headers?
There is a service provider that provides CORS headers (Access-Control-Allow-Origin: *) for javascript based requests:
https://freegeoip.com
Test the following XMLHTTP request for a sample:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
}
};
xhttp.open("GET", "//freegeoip.net/json/?callback=", true);
xhttp.send();
Or in case of jQuery Use:
$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
console.log(data);
});
I followed this article to connect to Azure via Rest where the first step is to get an access-token for the service. So i tried to send the following request:
POST https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: wamsprodglobal001acs.accesscontrol.windows.net
Content-Length: 120
Expect: 100-continue
Connection: Keep-Alive
Accept: application/json
grant_type=client_credentials&client_id=ams_account_name&client_secret=URL_encoded_ams_account_key&scope=urn%3aWindowsAzureMediaServices
and replaced the client_id and key(encoded) in the data to be posted.
But Chrome promptly complains about setting the unsafe Host-, Content-Length-, Connection- and Expect-Headers. So i omitted those and end up with the following:
xhr = new XMLHttpRequest();
xhr.open("POST", "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "application/json");
xhr.send("grant_type=client_credentials&client_id=<id>&client_secret=<encodedSecret>scope=urn%3aWindowsAzureMediaServices");
now upon sending the request i get:
XMLHttpRequest cannot load https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://nope.com' is therefore not allowed access.
But the request works when i send it through the Rest Client, Fiddler and requestmaker.com which i take as evidence that the request is formed correctly ...
Any hint as to how i can get this to work would be greatly appreciated.
Try the following (generated from POSTMAN)
var data = "grant_type=client_credentials&client_id=<ACOUNTNAME>&client_secret=<ACCOUNTKEY>&scope=urn%3AWindowsAzureMediaServices";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("host", "wamsprodglobal001acs.accesscontrol.windows.net");
xhr.setRequestHeader("connection", "Keep-Alive");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
In Postman, i have to have the Interceptor plugin enabled for this to work though, and disable Automatically Follow Redirects. See if that helps at all.
After you get the response back and parsed the access_token, you can use it in the next call to get the closest API endpoint like this
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://media.windows.net/");
xhr.setRequestHeader("x-ms-version", "2.11");
xhr.setRequestHeader("authorization", "Bearer <ACCESS_TOKEN>");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
I have an API I am trying to interface with that requires a custom content-type header be set, with the value text/xmlmc
I've implemented this like so
Xmlmc.prototype.submitRequest = function (request,callback) {
var self = this;
var port = portMap[request.service] || 5015;
var endpoint = this.endpoint = 'http://' + this.server + ':' + port;
var xml = request.toXml();
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// IE 5 and 6 makes us sad. Please don't use it
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//handle request
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
var response = self.handleResponse(xhttp);
callback(response);
}
};
xhttp.open('POST',endpoint,true);
xhttp.setRequestHeader('Content-type', 'text/xmlmc');
//xhttp.setRequestHeader('Content-length', xml.length.toString());
if(this.sessionCookie != '') {
xhttp.setRequestHeader('Cookie', this.sessionCookie);
}
xhttp.send(xml);
};
The endpoint is localhost:5015
When I do this, the request fails and never even sends. When I use a standard request header like 'text/plain' the request is sent but returns a status code of 501 not implemented. How can I set a custom HTTP header in an xmlhttprequest?
It turns out this was due to a cross origin issue. Even when the domain is the same, if the ports are different it is a problem. I fixed the issue by adding a reverse proxy to my apache configuration and now I can query the api without cross origin requests. Unfortunately I don't have access to change the API and allow cross origin domains.
I have a simple request I make to my service:
var request = new XMLHttpRequest();
request.open("OPTIONS", url, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.setRequestHeader('Accept', 'application/json');
request.onreadystatechange = function () {
if (request.readyState != 4) {
return;
}
var authType = request.getResponseHeader("WWW-Authenticate");
makeRequest(...);
};
request.send();
}
So what I'm trying to achieve is make a call to my endpoint to see what's the authorisation type (basic or bearer) and then when I get the auth type I will make the actual request with the proper credentials.
If I make the request manually I get the 401 unauthorised which is normal but I also get the WWW-Authenticate: Basic ... in my headers. However if I do this javascript call it will just fail with 401:unauthorised but I don't get this failed response in my callback so the authType will be undefined.
I haven't used javascript before so the question is how can I get the response in the callback even if the request failed with unAuthorised ?
XMLHttpRequest has an onerror callback that you can use:
var request = new XMLHttpRequest();
...
request.onerror = function(){
if (this.status == 401) {
}
}
...
request.send();