I want to extract a page by javascript (client based language) the problem is the third-part remote url doesnt not allow ajax request when i do this req without the header X-REQUESTED-WITH it gives the expected data with 200 Success in response but when i req it with that header it give 403 Forbidden with no content in respone .
i want to know how to req a page without the header X-REQUESTED-WITH in javascript , ajax , jquery or any client based language .
Please help me .
thanks
The X-REQUESTED-WITH header is not "standard". jQuery for instance will add it manually.
So by doing a default XHR request
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if( xhr.readyState === 4 ) {
console.log('done');
}
};
xhr.open('GET', 'hello=50', true);
xhr.setRequestHeader('FOO', 'BAR');
xhr.send(null);
there will not be this header. In the above simplified example we added a custom FOO request header instead, that is the same thing like jQuery adds the X-REQUESTED-WITH header into its ajax requests.
Related
My goal
I am doing .aspx file on Microsoft Visual Studio. What I expect is that the system will scan the QR code and then send the JSON data to the server side.
PS. I am using XMLHttpRequest to send the data.
What I Get
First I tried to pass it directly, it does not work so I check its status and readyStats, what it shows is 1(open) and 0(not initialized) (I am expecting 4(done) and 200(ok)) the responseText is null. I then inspected my browser (Google Chrome), the console shows an error "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
What I tried
So I searched for solution on stack overflow, most of them says that I need to put in the header Access-Control-Allow-Origin:* to the server, but the problem is I do not have the control of the server but I do contacted them to change the code to try it out, end up Access-Control-Allow-Origin:* doesn't work so I looked for alternative. I tried to use plugin such as Moesif Origin & CORS Changer but it shows "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.".
Below is my code:
function onScanSuccess(qrCodeMessage) {
...
var url = "https://Website-A.aspx";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
//I hardcoded the data for testing
var data = {
"SOME_ID": "Value",
"SOME_TYPE": "Value",
"SOME_ID": "Value",
"SOME_AMT": "Value",
"SOME_AMT_CURRENCY": "Value",
"SOME_DESC": "Value",
...
};
xhr.send(data);
}
Is there anyway to solve this without changing the server side's code or bypassing the CORS?
I wish to solve this by modify the code in the same .aspx only, is it possible?
If my code ain't going to work, is there any other way to do it?
Any helps will be appreciated.
cors must be allowed on server side. your code looks ok.
sorry, i can't use the comment function yet
I'm hosting a website that has a number of different domain names pointing at it.
lets call the hosted website example.com and the url-forwarded domain names - example-x.com, example-y.com, example-z.com
When the url-forwarded domains are visited, cross domain requests are made back to the host site, example.com.
I'm currently making ajax GET requests to json files and receiving the following error;
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://example-x.com' is therefore not allowed
access.
Even though the preflight OPTIONS return a status of 200 and the GET method returns a status of 200.
OPTIONS;
GET
I have set the following CORs headers on the host htaccess;
# <IfModule mod_headers.c>
SetEnvIfNoCase Origin "https?://(www\.)?(example-x\.com|example-y\.com|example-z\.com)(:\d+)?$" ACAO=$0
Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO
Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range"
Header set Access-Control-Allow-Credentials true
# </IfModule>
And i'm call GET using the following ajax request;
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
var url = 'http://example.com/data.json';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.setRequestHeader('Accept', 'application/json, text/javascript');
xhr.onload = function() { console.log('success');};
xhr.onerror = function() { console.log('error'); };
xhr.send();
EDIT
Removing setRequestHeader("Content-Type", "application/json; charset=UTF-8") from the ajax request has removed the preflight requirement, however the CORs error still persists, the screenshot below shows the request / response of GET, its my guess that the correct htaccess headers have not been set on the RequestURL - http://example.com/cms/wp-content/uploads/2017/04/preloader_data.json
GET - WITHOUT OPTIONS PREFLIGHT
You are trying to retrieve a json by a GET request. This should be a simple request, and it does not need to have a preflight request.
If you look at the requirements for a preflight request from MDN, you can see that setting Content-Type other than application/x-www-form-urlencoded, multipart/form-data or text/plain will cause this preflighted request.
If you look at the content-type from the RFC, it is a "SHOULD" for "a message containing a payload body". But your get request does not have a payload. As a result remove that header from your ajax call.
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>
I'm trying to get a token from the ArcGIS Online service using a Javascript. However, it's always returning an error which indicates the client_id isn't specified.
Am I doing everything right here?
<script type="text/javascript">
var MyJSONText = '{"client_id":"<<MY_CLIENT_ID>>","client_secret":"<<MY_CLIENT_SECRET>>","grant_type":"client_credentials","expiration":"1440","f":"json"}';
var MyJSON = JSON.parse(MyJSONText);
xhr = new XMLHttpRequest();
xhr.open("POST", "https://www.arcgis.com/sharing/rest/oauth2/token/");
xhr.send(MyJSON);
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
alert(xhr.responseText);
}
}
</script>
Edit - full error is:
{"error":{"code":400,"error":"invalid_request","error_description":"client_id not specified","message":"client_id not specified","details":[]}}
I was able to retrieve an access token using application/x-www-form-urlencoded request:
POST https://www.arcgis.com/sharing/rest/oauth2/token HTTP/1.1
User-Agent: Fiddler
Content-Type: application/x-www-form-urlencoded
Host: www.arcgis.com
Content-Length: 126
client_id=<YOUR ID>&client_secret=<YOUR SECRET>&grant_type=client_credentials&expiration=1440&f=json
which means that you might need to specify the Content-Type request header when making the XHR request:
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
and of course properly formatting the body as application/x-www-form-urlencoded instead of JSON. In my tests this endpoint didn't work with JSON payload.
Unfortunately from what it looks, the token endpoint doesn't support setting the Content-Type request header in its CORS policy which means that you might be out of luck in calling it with javascript. Besides their documentation doesn't mention anything about javascript as a supported language.
So basically if you want to make this work you could get the access token on your server side and pass it along to the client.
Access Token Generation Url =>https://www.arcgis.com/sharing/rest/oauth2/token
Headers
enter image description here
For the Case of body in Post man select 'x-www-form-urlencoded'
enter image description here
After that you will get the respective expected result with token
{"access_token":"S-z3mxAqsZBeihx8NgFmNGsZAUGfzKZWCYVV2TiQO422u9XDLTCTZAkpoecyxx_LAc71I_tPkeeOlo2Pzkapv01bBOA03SzMRjRMOm-h3ljTl-pb3XdffoyYjCflE4F8LD377DbpjDWkupkdTaxJpg..","expires_in":7200}
How do i detect laravel response header?
My javascript to check is but it doesn't work
if (xhr.getResponseHeader('location'))
{
console.log(xhr.getResponseHeader('location'));
}
and this is my server code to redirect
Redirect::guest('landing');
Try this javascript to get the headers of the current page:
var request = new XMLHttpRequest();
request.open('HEAD', document.location, false);
request.send(null);
console.log(request.getAllResponseHeaders());
Than you can see if there is a laravel header being sent or not