"CORS issue- 403 forbidden" using xmlhttprequest in javascript [duplicate] - javascript

This question already has answers here:
CORS error even after setting Access-Control-Allow-Origin or other Access-Control-Allow-* headers on client side
(2 answers)
Closed 1 year ago.
I'm trying to connect api hosted on cloud and getting 403-Forbidden due to CORS issue.
var url = "https://spring-demo-ysyfl4f26q-uc.a.run.app/getsummary";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}else{
myFunction('errorcode'+this.status+' error'+this.readyState+this.responseText);
}
};
xmlhttp.open('GET', url);
xmlhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
xmlhttp.setRequestHeader('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, HEAD, OPTIONS');
xmlhttp.setRequestHeader('key', 'PRODUCT');
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type, key,Access-Control-Allow-Headers,Access-Control-Allow-Origin, X-Requested-With');
xmlhttp.withCredentials = false;
xmlhttp.send();
script.js:75 GET https://spring-demo-ysyfl4f26q-uc.a.run.app/getsummary 403 (Forbidden)
Can anyone help in this, i'm able to get response via POSTMAN ? TIA

Enable CORS in cpanel
to enable CORS in your hosting account.
you can enable it adding the following lines in the .htaccess file in your hosting account.
<IfModule mod_headers. ...
Header set Access-Control-Allow-Origin "*"
</IfModule>
​
​

Related

No 'Access-Control-Allow-Origin' header is present on the requested resource when sending post request [duplicate]

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
cors issue on github oauth
(1 answer)
Closed 2 years ago.
I try to use github oauth 2.0. As my website doesn't have a backend, I use XMLHttpRequest to send a post request, but I get the following error when sending post request to get access_token:
Access to XMLHttpRequest at 'https://github.com/login/oauth/access_token' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here's my source code.
index.html
login
functions.js
function getQueryVariable(variable) {} //This works well.
function sendPost()
{
var http = new XMLHttpRequest();
var url = 'https://github.com/login/oauth/access_token';
var params = 'client_id=xxx&client_secret=xxx&code='+code;
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
login.html
<script src=functions.js></script>
<script>
var code=getQueryVariable("code");
console.log(code);
</script>
<script>
sendPost();
</script>
Please do a quick read-up on CORS.
Most likely .. you have enable CORS.
https://www.w3.org/wiki/CORS_Enabled

Can I a POST below code to any othes domain? [duplicate]

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
Request succeeds on server but results in CORS error in browser
(2 answers)
Closed 3 years ago.
Is it possible to make an HTTP POST request from JavaScript to any
domain name?
Javascript
var xhr = new XMLHttpRequest();
xhr.open("POST", 'URL linki', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
and I would like print on the screen. Is it possible?
Yes, it's possible to make a request to any domain as long as the domain in question accepts the request, and the server allows CORS (Cross-Origin Resource Sharing). The latter is only required if you want a response, as you're sharing resources across origins.

CORS - No 'Access-Control-Allow-Origin' header is present

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.

Laravel cross site AJAX post with session. Working but with JavaScript error?

I'm doing a cross site AJAX post to a laravel website while maintaining the session. This is the JS on the client website and the laravel middleware on my server.
Client js
var formData = new FormData();
formData.append('Referer', document.referrer);
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "https://mywebsite.com/record");
xmlHttp.withCredentials = true;
xmlHttp.send(formData);
Server middleware
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', $request->header('Origin'))
->header('Access-Control-Allow-Credential', 'true')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
It seems to be working fine in the 3 browsers I've tested it in so far however it does seem to throw up an error of
XMLHttpRequest cannot load https://mywebsite.com/record. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://clientwebsite.com' is therefore not allowed access.
This is what the server sends back in fiddler.
Access-Control-Allow-Origin: http://clientwebsite.com
Access-Control-Allow-Credential: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Two questions.
Question 1
First I can't understand why its saying its not working when I know it is? I can see the requests making it to the server then populating my database and I can see them being sent in fiddler.
Question 2
There is obviously something wrong with the headers but I'm not sure what?
I can see someone else has had the same issue but I wasn't able to make sense of the answer and I tried changing the header to "Access-Control-Allow-Credentials = true".
Credentials flag is 'true', but the 'Access-Control-Allow-Credentials

How to get some page by url in javascript

I want to get page from web-site using javascript.
I have url like:
http://not-my-site.com/random
From 'random' I will be redirected to another (random) page on the web-site.
Postman do everything like I want :) It's get whole page (html). But how can I do the same from javascript?
I tried CORS alredy following this guide http://www.html5rocks.com/en/tutorials/cors/ but without success. I still just get an error:
XMLHttpRequest cannot load http://not-my-site.com/random.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Code from tutorial:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', 'http://not-my-site.com/random');
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.onload = function() {
var responseText = xhr.responseText;
console.log(responseText);
// process the response.
};
xhr.onerror = function() {
console.log('There was an error!');
};
xhr.send();
And also I tried common xhr like this (got the same error):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://not-my-site.com/random', true);
xhr.send();
This seems to be a problem of CORS not being configured correctly on the server. The below PHP code should allow any request from any domain. (If you're not using PHP, it should be easy to convert the below code into any other language, the clue is to write to the HTTP header).
Remember to place this code before any HTML is outputted.
$origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:$_SERVER['HTTP_HOST'];
header('Access-Control-Allow-Origin: '.$origin);
header('Access-Control-Allow-Methods: POST, OPTIONS, GET, PUT');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, X-Requested-With');
header('P3P: CP="NON DSP LAW CUR ADM DEV TAI PSA PSD HIS OUR DEL IND UNI PUR COM NAV INT DEM CNT STA POL HEA PRE LOC IVD SAM IVA OTC"');
header('Access-Control-Max-Age: 1');
Accepting requests from all domains is insecure. For a better (but slightly more complex) solution, see here: CORS That Works In IE, Firefox, Chrome And Safari

Categories

Resources