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.
Related
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>
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
This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 2 years ago.
I need your assistance please because I have a CORS error when attempting to upload from a drag and drop image(s) uploader. It errors out on CORS issues. The drag and drop works which means it seems like the actual upload is the only failure.
I need to know what workaround or other solution there might be.
The error message in console:
Access to XMLHttpRequest at 'https://domain1.com/upload' from origin 'https://domain2.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
My dashboard (therefore this script), is on one domain (domain1.com) and the file(s) is/are to be uploaded to domain2.com/upload, that being the domain on which I store all the static files.
[edit]afterthought: Is the link correct? Should it be a link to a script or to the image dir?[/edit]
Heres the javascript
function uploadFile(file, i) {
//var url = 'https://api.cloudinary.com/v1_1/joezimim007/image/upload'
var url = "domain2.com/upload"
var xhr = new XMLHttpRequest()
var formData = new FormData()
xhr.open('POST', url, true)
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
// Update progress (can be used to show progress indicator)
xhr.upload.addEventListener("progress", function(e) {
updateProgress(i, (e.loaded * 100.0 / e.total) || 100)
})
xhr.addEventListener('readystatechange', function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
updateProgress(i, 100) // <- Add this
//console.log('xhr ready state : ' + xhr.readyState );
}
else if (xhr.readyState == 4 && xhr.status != 200) {
// Error. Inform the user
//console.log('upload error ' );
//console.log( 'xhr ready state : ' + xhr.readyState);
}
})
formData.append('upload_preset', 'ujpu6gyk')
formData.append('file', file)
xhr.send(formData)
}
Add the "proxy" property (found at the bottom here) to package.json:
"proxy": "http://localhost:<PORT-GOES-HERE>"
Now, instead of making HTTP requests like this:
axios.get("http://localhost:8080/example")
You should write them like this:
axios.get("/example")
or
Also you can install CORS plugins for Chrome ("Moesif COR"S or "Allow CORS") or also you can add your front-end domain to allow hosts on your back-end.
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.
This question already has answers here:
Cross origin requests are only supported for HTTP but it's not cross-domain
(9 answers)
Closed 7 years ago.
I have been using an HTTP request in a JS file to retrieve information from a local JSON file. It works just fine on my Windows computer in Firefox and Chrome, but when run on a Mac, the Chrome debugger throws an error saying that Cross origin requests are only supported for HTTP...
My HTTP request code is as follows:
var xhr = new XMLHttpRequest();
xhr.open("GET", "sample.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var status = xhr.status;
if ((status >= 200 && status < 300) || status === 305) {
var myData = JSON.parse(xhr.responseText);
window.myData = myData;
showAll(myData);
}
}
};
xhr.send(null);
Any ideas? Thanks
Yes, this is a security issue. You need to run this on a server, and the file:/// protocol is not supported for such kind of requests! AJAX is a proper HTTP request response kind of concept and you cannot use file:/// protocol or use different protocols for the transaction.