Get client IP in javascript/angularjs - javascript

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);
});

Related

Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I'm using WordPress and from the code i have added a json get request.
This json result is hosted on other server in asp.net platform below is my code :
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('....api/data/Getallunits', function(err, data) {
mydata = data;
});
I'm getting this error:
"Access to XMLHttpRequest at '...../api/data/Getallunits' from origin 'mywordpress' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
Is there anything can be done by adding in wordpress, any phpcode or any plugin
i tried with WP-CORS plugin but didn't worked, please advice if any code should be added on the json get request or any other edits.

Writing Request Payload property on httprequest

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

XMLHttpRequest response: preflight request does not pass the access control check:

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.

XMLHttpRequest doesn't send some headers

The title explains my problem clearly. I am testing the AJAX requests of my application but I cannot send some headers, for example Authorization header.
For testing I use this endpoint to echo me the headers I sent. Here is my javascript code:
var loadDoc = function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
console.log(JSON.parse(this.responseText));
};
}
xhttp.open("GET", "http://headers.jsontest.com/", true);
xhttp.setRequestHeader("Authorization", "JWT token");
xhttp.send();
}
I can send the exact same request with python's requests module. But I can't send it with XMLHttpRequest. XMLHttpRequest can send the Content-Type header and the server echoes me the headers but not Authorization.
What is going on here?

Setting a custom content-type xmlhttprequest

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.

Categories