Cannot assign "Access-Control-Allow-Origin" in XmlHttpRequest - javascript

I am trying to make a request to ping my backend api with XMLHttpRequest.
Following is my code
var r = new XMLHttpRequest();
r.open("POST", 'domain:port/path/');
r.setRequestHeader("Access-Control-Allow-Origin", '*');
r.setRequestHeader("Accept", 'application/json ');
var data = {"key":"value"};
r.send(data);
But I always accept the following error message
Access to XMLHttpRequest at 'domain:port/path/' from origin
'http://localhost:8000' 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.
Firstly; I think that's because I didn't set "Access-Control-Allow-Origin". But even I set it, it's not working.
How can I solve my problem?
Thanks.

From MDN
The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given origin
it is a response header, you need to set Access-Control-Allow-Origin on your server-side code

Access-Control-Allow-Origin is a response header, not a request header.
Your server decides what origins are allowed to access it. If it were that easy to bypass, would it really be a security measure? :-)
If what you truly want is for that endpoint to allow any domain to access it, then you have to add the header, there.

Related

CORB: Cross-Origin Read Blocking on JSFiddle

I added https://unpkg.com/htmx.org#1.3.3/dist/htmx.min.js.gz to my jsfiddle, but now I get:
CORB: Cross-Origin Read Blocking
Is there a way to work around this?
JSFiddle: https://jsfiddle.net/thomas_guettler/7cLy8m5u/3/
Code:
<button
hx-get="https://raw.githubusercontent.com/guettli/html-fragments/main/fragments/simple-div.html">
Press me
</button>
If I use this URL: https://unpkg.com/htmx.org#1.3.3/dist/htmx.min.js
then I get
Access to XMLHttpRequest at 'https://raw.githubusercontent.com/guettli/html-fragments/main/fragments/simple-div.html' from origin 'https://fiddle.jshell.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I found a work-around.
If I use a mocky endpoint, then it works.
For example: https://run.mocky.io/v3/6f4b9b4c-4ac9-44e0-89fa-da7d222346df
I guess this http header in the response of github makes the browser reject the snippet:
Referrer Policy: strict-origin-when-cross-origin

Angular 4 No 'Access-Control-Allow-Origin' header is present on the requested resource Bittrex [duplicate]

Json issues with javascript and jquery.
Trying to load some JSON using javascript.
I have it working using:
See it here: http://jsfiddle.net/5pjha/789/
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
$.getJSON(url, function (json) {
alert(JSON.stringify(json.results));
});
But it dosnt work on the following urls, why is this?
https://poloniex.com/public?command=return24hVolume
https://bittrex.com/api/v1/public/getmarkets
https://api.mintpal.com/v1/market/summary/
Are the following urls not correct JSON ?
Thanks
The google's api set the Access-Control-Allow-Origin header to *, so you could access it by cross domain.
While other urls you provided do not, so you will got an error like below:
XMLHttpRequest cannot load https://api.mintpal.com/v1/market/summary/.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://fiddle.jshell.net' is therefore not allowed
access.
I believe the issue is down to whether or not the servers you are requesting your JSON from have cross-origin resource sharing (CORS) enabled.
you can see in the headers from the google service that they set Access-Control-Allow-Origin:* This is not the case for teh other URL's you list.
To get around this you will need some form of proxy so that you can request from a server either on the same domain or a server that enables CORS.
For ajax request to any server, You need to define Access-Control-Allow-Origin header for client. which is absent in given. You need to define origin of XMLHttp request in server who can request.
For more info refer this link

Why does the browser allow xorigin POST but not PUT?

Consider the very simple example of using XMLHttpRequest.
The following posts properly ( you can see it in the network tab or by directing your browser to http://requestb.in/yckncpyc) although it prints a warning to the console
XMLHttpRequest cannot load http://requestb.in/yckncpyc. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
const method = "POST"
const req = new XMLHttpRequest()
req.open(method, 'http://requestb.in/yckncpyc')
req.send("foobar")
console.log("sent")
req.addEventListener('load', function() { console.log(req.status, req.response) })
Sure. I get that. What I don't get is why merely changing the verb used to a PUT results in something completely different. The request sent is an OPTIONS preflight request and prints
XMLHttpRequest cannot load http://requestb.in/yckncpyc. 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.
const method = "PUT"
const req = new XMLHttpRequest()
req.open(method, 'http://requestb.in/yckncpyc')
req.send("foobar")
console.log("sent")
req.addEventListener('load', function() { console.log(req.status, req.response) })
Why does the browser* treat these differently? It seems like something that would be done for security but that really makes no sense since an attacker can always use a POST instead of a PUT.
So what is the logic here?
Tried this in Chrome 52, Safari 9.1.2
GET, HEAD, and POST requests (with a couple other restrictions) can be made cross-origin with no additional communication. The responses cannot be examined, but the requests are allowed.
Anything else requires a preflight request to check the headers from the target site to see whether the request would be allowed.
The reason for such a setup is that GET, HEAD, and POST were historically allowed from browsers as a natural part of HTML semantics. Tags for scripts and CSS and images do GET requests, and forms do POSTs. When the CORS stuff was introduced, therefore, those were allowed under the assumption that sites were no more vulnerable to simple requests like that in an XHR world then they were in the simpler non-XHR world.
So simple requests are allowed, and the browser looks at the response headers to decide whether the requesting code in the cross-origin page should be allowed to see the response content. For other requests, the browser first sends an OPTIONS request to check the CORS response headers. Only if that looks OK (that is, if the response headers contain the appropriate "yes that's OK" headers) will the XHR be allowed to proceed.

Cross domain post json without preflight

I am trying to post some json to a sharepoint url, as in this example. The example uses node, but I am trying to do it in the browser.
I tried it with fetch first:
fetch("https://outlook.office365.com/webhook/...",
{
method: 'POST',
headers: {
'Content-Type': 'application/json;'
},
body: JSON.stringify(this.groupCardBody()),
})
From that i got the error:
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:1234' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
But i don't have control over the response, and if i add mode: 'no-cors' into the fetch options as it suggests, it strips the content-type header and returns 415 Unsupported Media Type.
So i tried it with a simple xhttp request and that fails too as it does the preflight and doesn't get the right headers back:
let xhr = new XMLHttpRequest()
xhr.open("POST", "https://outlook.office365.com/webhook/...");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(this.groupCardBody()));
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
The request library used in the example was quite difficult to get working in the browser and by no means lightweight (added almost 2MB to my webpacked script), so any suggestions about how to get round this are welcome I am pretty stuck, all my searches turn up answers for fixing the server and i don't have that option.
UPDATE
As suggested in the accepted answer, I solved it by posting the json back to the server and making the post from there, got it working with something as simple as the following:
Client:
fetch("PostGroupCard?json="+
encodeURI(JSON.stringify(this.groupCardBody())),
{credentials: "same-origin"}
)
Server:
Function PostGroupCard(json As String)
Dim wr = WebRequest.Create("https://outlook.office365.com/webhook/...")
wr.ContentType = "application/json"
wr.Method = "POST"
Using sw = New StreamWriter(wr.GetRequestStream())
sw.Write(json)
sw.Flush()
sw.Close()
End Using
Dim r = wr.GetResponse()
Using sr = New StreamReader(r.GetResponseStream())
Dim result = sr.ReadToEnd()
End Using
End Sub
Most of this answer is taken from the comments.
For security reasons, you cannot make an XMLHTTPRequest unless you are on the same origin or CORS header from the other domain says you can. If this were possible, any site could preform malicious actions like hack you accounts.
Two alternatives to consider would be JSONP and having your server act as a proxy to access the other domain.

getting json from external source in javascript

Json issues with javascript and jquery.
Trying to load some JSON using javascript.
I have it working using:
See it here: http://jsfiddle.net/5pjha/789/
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
$.getJSON(url, function (json) {
alert(JSON.stringify(json.results));
});
But it dosnt work on the following urls, why is this?
https://poloniex.com/public?command=return24hVolume
https://bittrex.com/api/v1/public/getmarkets
https://api.mintpal.com/v1/market/summary/
Are the following urls not correct JSON ?
Thanks
The google's api set the Access-Control-Allow-Origin header to *, so you could access it by cross domain.
While other urls you provided do not, so you will got an error like below:
XMLHttpRequest cannot load https://api.mintpal.com/v1/market/summary/.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://fiddle.jshell.net' is therefore not allowed
access.
I believe the issue is down to whether or not the servers you are requesting your JSON from have cross-origin resource sharing (CORS) enabled.
you can see in the headers from the google service that they set Access-Control-Allow-Origin:* This is not the case for teh other URL's you list.
To get around this you will need some form of proxy so that you can request from a server either on the same domain or a server that enables CORS.
For ajax request to any server, You need to define Access-Control-Allow-Origin header for client. which is absent in given. You need to define origin of XMLHttp request in server who can request.
For more info refer this link

Categories

Resources