Chrome Extension blocked from a rails API - javascript

I am just trying to talk with a REST api on a Rails site.
I am using a Chrome extension and javascript to make a CORSRequest.
I get this error whenever I try to make a request:
XMLHttpRequest cannot load https://MYWEBSITE.com/api/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://mychomreextensioncode' is therefore not allowed access. The response had HTTP status code 404.
Here is my current code:
function makeCorsRequestLogin() {
var url = "https://MYWEBSITE.com/api/login";
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = function() {
var text = xhr.responseText;
var title = text; //getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onerror = function() {
alert('Woops, there\'s an error making the request.');
};
var password = document.getElementById("password").value;
var user_name = document.getElementById("username").value;
xhr.send(JSON.stringify({"user_name":user_name, "password":password}));
}
Elsewhere, in the past, people have said that this code solves it. But, I have no idea where this could would go.
# This is used to allow the cross origin POST requests made by confroom kiosk app.
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = "*"
headers['Access-Control-Request-Method'] = %w{GET POST OPTIONS}.join(",")
end
I am only working in JS and HTML on a chrome extension. I do not have access to the ruby site. Can I solve this problem from only my end?

You should define permission for your server domain in the manifest.json.
"permissions": ["https://MYWEBSITE.com/*"]
Also make sure you set the right protocol whether it's http or https.

Related

Access-Control-Allow-Origin' header contains multiple values 'http://xx.xx.xx.xx:3002, http://xx.xx.xx.xx:3002', but only one is allowed

I have downloaded a windows executable file and I installed it. The service will be listening on localhost:11100 port.
I have a written a javascript code to connect to the port and running this javascript code on any webserver is failing, because server sending multiple Access-Control-Allow-Origin headers in the response.
But if I write my JavaScript code in plain html page locally and open it in browser then it is sending one 'Access-Control-Allow-Origin' in the response.
Below is the Javascript code:
function RDService(){
var url = "http://127.0.0.1:11100";
var xhr;
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number{
//IE browser
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} else {
//other browser
xhr = new XMLHttpRequest();
}
xhr.open('RDSERVICE', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
var status = xhr.status;
if (status == 200) {
alert(xhr.responseText);
//Capture(); //Call Capture() here if FingerPrint Capture is required inside RDService() call
console.log(xhr.response);
} else {
console.log(xhr.response);
}
}
};
xhr.send();
}
after calling the RDService function below error is throwing by the service:
Failed to load http://127.0.0.1:11100/: Response to preflight request
doesn't pass access control check: The 'Access-Control-Allow-Origin'
header contains multiple values 'http://xx.xx.xx.xx:3002,
http://xx.xx.xx.xx:3002', but only one is allowed. Origin
'http://xx.xx.xx.xx:3002' is therefore not allowed access.
The windows executable should only be returning one domain or * in the Access-Control-Allow-Origin header. This is not an issue with the client side JavaScript.
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: <origin>
*
For requests without credentials, the server may specify "*" as a wildcard, thereby allowing any origin to access the resource.
<origin>
Specifies a URI that may access the resource.
reference:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Response to preflight request doesn't pass access control check error

The exact error that I am struggling with is "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.".
I am trying to fetch JSON data using JavaScript from https://api.kraken.com/0/public/OHLC?pair=ETHEUR. I created a XMLHttpRequest object to do this, and specified GET as the type of request. This is supposedly a simple request, however the error says that a preflight request was sent. What is the reason for this behavior? That being said, to fix this error I tried to set a request header in which I specified '*' as the value for the Access-Control-Allow-Origin, yet I still get an error. I have looked through responses to similar questions as mine, but haven't been able to figure out how to solve the problem I am dealing with. This is probably due to still being very new to JavaScript. Either way, below is the code that I have written:
var requestURL = 'https://api.kraken.com/0/public/OHLC?pair=ETHEUR'
var request = new XMLHttpRequest();
request.open('GET',requestURL,true);
request.responseType = 'json';
request.onload = function(){
var data = request.response;
console.log(data);
}
request.setRequestHeader('Access-Control-Allow-Origin','*');
request.send();
In cases like this where the server you’re trying to make a cross-origin request to doesn’t send the Access-Control-Allow-Origin response header, your only option, if you want to make a request to that server from frontend JavaScript code running in a browser, is to use a CORS proxy. Otherwise, your browser won’t allow your frontend JavaScript code to access the response.
So, you can make your request succeed if you change your code to have something like this:
var proxyURL = 'https://cors-anywhere.herokuapp.com';
var requestURL = 'https://api.kraken.com/0/public/OHLC?pair=ETHEUR';
var request = new XMLHttpRequest();
request.open('GET', proxyURL + '/' + requestURL, true);
That sends the request through https://cors-anywhere.herokuapp.com, which forwards the request to https://api.kraken.com/0/public/OHLC?pair=ETHEUR and then receives the response. The https://cors-anywhere.herokuapp.com backend adds the Access-Control-Allow-Origin header to the response and passes that back to your requesting frontend code.
The browser will then allow your frontend code to access the response because that response with the Access-Control-Allow-Origin response header is what the browser sees.
You can also easily set up your own CORS proxy using https://github.com/Rob--W/cors-anywhere/
Note also that request.setRequestHeader('Access-Control-Allow-Origin','*') needs to be removed from the frontend code you are making the request with (as mentioned in comments above).
That’s because Access-Control-Allow-Origin is strictly a response header for servers to send in responses; sending it from the client side in a request will have no effect other than to trigger your browser to do an unnecessary CORS preflight OPTIONS request that will fail.
For details about what browsers do when you send cross-origin requests from frontend JavaScript code using XHR or the Fetch API or AJAX methods from JavaScript libraries—and details about what response headers must be received in order for browsers to allow frontend code to access the responses—see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
var proxyURL = 'https://cors-anywhere.herokuapp.com';
var requestURL = 'https://api.kraken.com/0/public/OHLC?pair=ETHEUR';
var request = new XMLHttpRequest();
request.open('GET', proxyURL + '/' + requestURL, true);
request.responseType = 'json';
request.onload = function() {
var data = request.response;
document.querySelector('pre').textContent = JSON.stringify(data, null, 2);
}
request.send();
<pre></pre>

MailChimp API 3.0 xhr subscribe 501 error

I am trying to subscribe users to my mailchimp list using this snippet:
function subscribeUser(name, email) {
var xhr = new XMLHttpRequest();
var endpoint = 'https://<dc>.api.mailchimp.com/3.0/lists/<list>/members/';
var data = {};
data.email_address = email;
data.status = "subscribed";
data.merge_fields = {};
data.merge_fields.NAME = name;
xhr.open("POST", endpoint, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "apikey <key>");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(data);
}
It generates this error in chrome:
I am unable to write ajax based services to update lists. Because you guys did not add the Access Control header. I cannot send a simple xhr to your endpoint using a modern browser.
XMLHttpRequest cannot load https://<dc>.api.mailchimp.com/3.0/lists/<list>/members/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 501.
Mine is a static website and I would like to keep it that way. No backend is needed, hosted on github. So I need a JS solution to this.
They currently do not allow client-side access to their API. Their response to a similar question in comments:
We do not support accessing the API via client-side Javascript to
avoid the security issue of passing your API Key along to your users.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://........

I am trying to communicate with an enterprise application from an web application mainly via javascript using ajax. I tried a lot to solve this issue but not succeeded. I saw several online httppost tool there I am able to see the response text but it is not happening from my end. Each time I am receiving an message like "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://url. (Reason: CORS header 'Access-Control-Allow-Origin' missing)."
My code:
var url = "use_url";
var method = "POST";
var regid = "null";
var UNAME = "abcd089";
var PASSWORD = "abcd007*";
var forLogin = "10 112 " +UNAME+ " " + PASSWORD + " " + regid + " 01";
var async = true;
var request = new XMLHttpRequest();
request.open('POST', url, async);
request.onload = function(){
//HTTP response
//if(request.readyState === 4 && request.status === 200){
var status = request.status;
var statusData = request.responseText;
console.log(status);
console.log(statusData);
console.log(request);
//}
};
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.setRequestHeader("Cache-Control", "no-cache");
request.send(forLogin);
I am looking for a solution to get response text. I saw online some solutions but they all are talking about setting response header, but some online httppost sites are working fine on data and producing response text. I am looking solution in javascript.
That is not allowed from javascript side if you are on different domain then you need to do at from server side.
browser has cross-origin blocked you can not do any request to non host domain from javascript using ajax.
if you are on http://XXXX.com then you can not call http://YYYY.com from javascript for post request
if you have full control over both domain that you can change your server config to allowed that domain to access resource but that is not preferable as security..
below code you can use to do http post request from server
URL url = new URL("your url");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
out.close();

How to make CORS request using XMLHttpRequest

$scope.readFile = function(url){
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
if (doc.responseText == undefined)
return;
$scope.loglines += doc.responseText;
}
}
doc.open("GET", url, true);
doc.send();
}
this is the code i used to get data from same origin using angularJS. how could i impore this to get data fron cross domain
To get data from cross domain, you can't do anything on client side, however you can set CORS on server side so that server allows you to send a cross origin request.
One other bad solution is to disable chrome same origin policy.
Disable same origin policy in Chrome

Categories

Resources