Why does my JavaScript get a “No 'Access-Control-Allow-Origin' header is present on the requested...
I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask. However, when I make the request, I get the following error:
XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?
This is the request code:
$.ajax({
type: "POST",
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain : true,
xhrFields: {
withCredentials: true
}
})
.done(function( data ) {
console.log("done");
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
jquery cors restful-authentication same-origin-policy flask-restless
|
show 6 more comments
I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask. However, when I make the request, I get the following error:
XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?
This is the request code:
$.ajax({
type: "POST",
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain : true,
xhrFields: {
withCredentials: true
}
})
.done(function( data ) {
console.log("done");
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
jquery cors restful-authentication same-origin-policy flask-restless
23
Are you doing the request from localhost or direcly executing HTML?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:31
@MD.SahibBinMahboob If I understand your question I do request from localhost - I have page on my computer and just run it. When I deploy site on hosting it's gave same result.
– Mr Jedi
Nov 17 '13 at 19:43
is the domain of your executed page and requested domain name same or different?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:47
4
much related: stackoverflow.com/questions/10143093/…
– cregox
Jul 7 '14 at 16:39
7
For anyone looking for more reading, MDN has a good article all about ajax and cross origin requests: developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
– Sam Eaton
Jun 18 '15 at 15:22
|
show 6 more comments
I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask. However, when I make the request, I get the following error:
XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?
This is the request code:
$.ajax({
type: "POST",
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain : true,
xhrFields: {
withCredentials: true
}
})
.done(function( data ) {
console.log("done");
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
jquery cors restful-authentication same-origin-policy flask-restless
I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask. However, when I make the request, I get the following error:
XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?
This is the request code:
$.ajax({
type: "POST",
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain : true,
xhrFields: {
withCredentials: true
}
})
.done(function( data ) {
console.log("done");
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
jquery cors restful-authentication same-origin-policy flask-restless
jquery cors restful-authentication same-origin-policy flask-restless
edited Jan 26 '18 at 20:16
John
5,654755111
5,654755111
asked Nov 17 '13 at 19:29
Mr JediMr Jedi
10.9k51931
10.9k51931
23
Are you doing the request from localhost or direcly executing HTML?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:31
@MD.SahibBinMahboob If I understand your question I do request from localhost - I have page on my computer and just run it. When I deploy site on hosting it's gave same result.
– Mr Jedi
Nov 17 '13 at 19:43
is the domain of your executed page and requested domain name same or different?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:47
4
much related: stackoverflow.com/questions/10143093/…
– cregox
Jul 7 '14 at 16:39
7
For anyone looking for more reading, MDN has a good article all about ajax and cross origin requests: developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
– Sam Eaton
Jun 18 '15 at 15:22
|
show 6 more comments
23
Are you doing the request from localhost or direcly executing HTML?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:31
@MD.SahibBinMahboob If I understand your question I do request from localhost - I have page on my computer and just run it. When I deploy site on hosting it's gave same result.
– Mr Jedi
Nov 17 '13 at 19:43
is the domain of your executed page and requested domain name same or different?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:47
4
much related: stackoverflow.com/questions/10143093/…
– cregox
Jul 7 '14 at 16:39
7
For anyone looking for more reading, MDN has a good article all about ajax and cross origin requests: developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
– Sam Eaton
Jun 18 '15 at 15:22
23
23
Are you doing the request from localhost or direcly executing HTML?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:31
Are you doing the request from localhost or direcly executing HTML?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:31
@MD.SahibBinMahboob If I understand your question I do request from localhost - I have page on my computer and just run it. When I deploy site on hosting it's gave same result.
– Mr Jedi
Nov 17 '13 at 19:43
@MD.SahibBinMahboob If I understand your question I do request from localhost - I have page on my computer and just run it. When I deploy site on hosting it's gave same result.
– Mr Jedi
Nov 17 '13 at 19:43
is the domain of your executed page and requested domain name same or different?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:47
is the domain of your executed page and requested domain name same or different?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:47
4
4
much related: stackoverflow.com/questions/10143093/…
– cregox
Jul 7 '14 at 16:39
much related: stackoverflow.com/questions/10143093/…
– cregox
Jul 7 '14 at 16:39
7
7
For anyone looking for more reading, MDN has a good article all about ajax and cross origin requests: developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
– Sam Eaton
Jun 18 '15 at 15:22
For anyone looking for more reading, MDN has a good article all about ajax and cross origin requests: developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
– Sam Eaton
Jun 18 '15 at 15:22
|
show 6 more comments
41 Answers
41
active
oldest
votes
1 2
next
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
5
You're right. I doing request to different domain than my page is. API is on server and I run request from localhost. Before I accept answer can you explain me what mean "executing the request directly" ? POSTMAN don't use domain?
– Mr Jedi
Nov 17 '13 at 19:54
144
The browser is not blocking the request. The only browsers that outright block cross-origin ajax requests is IE7 or older. All browsers, other than IE7 and older, implement the CORS spec (IE8 & IE9 partially). All you need to do is opt-in to CORS requests on your API server by returning the proper headers based on the request. You should read up on CORS concepts at mzl.la/VOFrSz. Postman sends requests via XHR as well. If you are not seeing the same problem when using postman, this means that you are unknowingly not sending the same request via postman.
– Ray Nicholus
Nov 17 '13 at 20:01
8
@MD.SahibBinMahboob Postman is NOT sending a request "from your java/python" code. It is sending the request directly from the browser. XHR in Chrome extensions does work a bit differently, especially when cross-origin requests are involved.
– Ray Nicholus
Nov 17 '13 at 20:08
9
@yves it's the browser who actually imposed the rule. So initiating request from any places rather than browser should work file
– MD. Sahib Bin Mahboob
Aug 5 '15 at 12:54
1
@SuhailGupta, if you allow origins in your server, it will be allowed to do the request which is actually known as CORS.
– MD. Sahib Bin Mahboob
Feb 29 '16 at 5:07
|
show 9 more comments
This is not a fix for production or when application has to be shown to the client, this is only helpful when UI and Backend development are on different servers and in production they are actually on same server. For example: While developing UI for any application if there is a need to test it locally pointing it to backend server, in that scenario this is the perfect fix. For production fix, CORS headers has to be added to the backend server to allow cross origin access.
The easy way is to just add the extension in google chrome to allow access using CORS.
(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)
Just enable this extension whenever you want allow access to no 'access-control-allow-origin' header request.
Or
In Windows, paste this command in run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
this will open a new chrome browser which allow access to no 'access-control-allow-origin' header request.
137
This is great but clients can't be asked to launch chrome this way to enforce an internal requirement for a webservice call.
– Taersious
Sep 24 '15 at 17:55
78
this shouldn't be accepted as an answer, installing a third party plugin to fix your app, rather than understanding CORS and fixing your app, how will other people use your api? will you make them all install this plugin
– James Kirkby
Apr 28 '16 at 11:10
4
I installed this extension and did a request, than checked the request in fiddler, the following was specified -> Origin: evil.com . Looks like this extension is changing the Origin to evil.com
– wagwanJahMan
May 10 '16 at 12:54
14
I think this is a really great answer if you don't need a permanent fix or if you only need CORS disabled temporarily. That's what I needed, and this solution worked great. Obviously, this could never be considered a permanent solution.
– jtcotton63
Mar 24 '17 at 0:44
2
This answer is fine. For dev work, this got me up-and-running asap and I will come back and find the proper fix later...
– Adam Hughes
Oct 19 '17 at 19:48
|
show 14 more comments
If you can deal with JSON in return, then try using JSONP (note the P at the end) for speaking between domains:
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ......
Learn more about working with JSONP here:
The advent of JSONP — essentially a consensual cross-site scripting hack — has opened the door to powerful mashups of content. Many prominent sites provide JSONP services, allowing you access to their content via a predefined API.
2
With NodeJs with datatype json worked, with ASP.Net this was the culprit
– Gaizka Allende
May 15 '14 at 9:36
84
Be aware jsonp doesn't work for POST content. More discussions here.
– Prabu Raja
Nov 13 '14 at 0:28
61
How does this have so many up votes when you cant use jsonp with POST requests?!?!
– fatlog
Aug 7 '15 at 15:06
8
When you useJSONP
, $.ajax will ignoretype
, so it's alwaysGET
which means this answer will always work.
– noob
Oct 6 '16 at 3:56
8
Also note that JSONP is not directly interchangeable with JSON. You need the server to return data in JSONP format too. Simply changing thedataType
in the AJAX request settings alone isn't going to work.
– Rory McCrossan
Sep 7 '17 at 10:19
|
show 4 more comments
It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:
<?php header('Access-Control-Allow-Origin: *'); ?>
Warning: This contains a security issue for your PHP file that it could be called by attackers. you have to use sessions and cookies for authentication to prevent your file/service against this attack. Your service is vulnerable to cross-site request forgery (CSRF).
If you are using Node-red you have to allow CORS in the node-red/settings.js
file by un-commenting the following lines:
// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
origin: "*",
methods: "GET,PUT,POST,DELETE"
},
314
The question was not about PHP at all.
– mknaf
Dec 10 '14 at 14:32
83
and it's not secure
– llazzaro
Dec 20 '14 at 19:25
112
You shouldn't turn off CORS because you don't know what its for. This is a terrible answer.
– meagar♦
Dec 30 '14 at 6:12
105
Even though it might not be secure, the question was not about security, but how to accomplish the task. This is one of the options that a developer has to choose from when dealing with cross-domain AJAX requests. It helped me resolve the issue, and for my application, I don't care where the data came from. I sanitize all the input with PHP on the destination domain, so, if someone wants to post some junk to it, let them try. The main point here is, cross-domain AJAX can be allowed from the destination domain. +1 for the answer.
– ZurabWeb
Feb 26 '15 at 16:37
18
While I agree with the general message Piero is giving, that it's not specifically about security, but security is a concern. I think this should have at least said something like "This is generally bad! Don't do this unless you know what you're doing! Here's more documentation on it: ...", and maybe briefly explain why. I would hate for someone to come on here and just think "Oh, I can just add/adjust this header and I'm good!" and not know the full ramifications. I mean, it's kind of on them to research and all, but still.
– Thomas F.
Oct 15 '15 at 14:55
|
show 9 more comments
I wish someone shared this site with me long ago http://cors.io/ it would have saved a ton of time compared to building and relying on my own proxy. However, as you move to production, having your own proxy is the best bet since you still control all aspects of your data.
All you need:
https://cors.io/?http://HTTP_YOUR_LINK_HERE
27
What are the downsides of this? Are those guys intercepting my data?
– Sebastialonso
Aug 21 '15 at 16:33
6
cors.io/?u=HTTP_YOUR_LINK_HERE (small correction)
– jkpd
Sep 17 '15 at 13:05
150
I don't think sending your data over 3rd party proxy is a good idea
– Daniel Alexandrov
Oct 16 '15 at 14:07
9
One downside is they are sometimes overloaded, as they are now.This application is temporarily over its serving quota. Please try again later.
– evelynhathaway
Feb 20 '16 at 7:52
17
try toohttps://crossorigin.me/http://example.com
– KingRider
Apr 15 '16 at 15:05
|
show 12 more comments
If you are using Node.js, try it:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
More information: CORS on ExpressJS
5
I am giving you the up vote because this is exactly what I needed. But think it is a bad idea to promote the "*" example without explaining that it will allow any connection and should not be used in production. This is explained at the MDN link developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
– rob
Jun 9 '17 at 9:12
@rob thanks for your comment. You are right, we should specify which origins are allowed to use the resources. But in case, the resources use for public purpose and we don't know the consumers, I think we should go with "*" if I am not wrong.
– Nguyen Tran
Jun 9 '17 at 11:08
I have used this concept and my issue is resolved in nodejs. Thanks
– Deepak Bhatta
Aug 20 '17 at 7:29
app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); res.setHeader('Access-Control-Allow-Credentials', true); if ('OPTIONS' === req.method) { res.send(204); } else { next(); } });
– Ricky sharma
Sep 26 '17 at 10:05
1
Regarding dangers of using"Access-Control-Allow-Origin", "*"
, see security.stackexchange.com/a/45677. tldr: W3 spec actually advises that: A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*"
– CODE-REaD
Feb 15 '18 at 16:45
add a comment |
There's a cross-domain issue using Ajax. You must be sure you are accessing your files on the same http://
path without www.
(or access from http://www.
and post to the same path including www.
) which the browser considers as another domain when accessing via a www.
path, so you see where the problem is. You are posting to a different domain and the browser blocks the flow because of the origin issue.
If the API is not placed on the same host that you are requesting from, the flow is blocked, and you will need to find another way to communicate with the API.
yup, i was forced to this in my phonegap app, var app_url = location.protocol + '//' + location.host+'/api/. the problem was the site with www. prepended would bring that error.
– Sir Lojik
Apr 27 '15 at 12:26
add a comment |
Because
$.ajax({type: "POST" - Calls OPTIONS
$.post( - Calls POST
both are different Postman calls "POST" properly but when we call it will be "OPTIONS"
For c# web services - webapi
Please add the following code in your web.config file under <system.webServer> tag. This will work
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Please make sure you are not doing any mistake in the ajax call
jQuery
$.ajax({
url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST", /* or type:"GET" or type:"PUT" */
dataType: "json",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
Angular 4 issue please refer : http://www.hubfly.com/blog/solutions/how-to-fix-angular-4-api-call-issues/
Note: If you are looking for downloading content from third party website then this will not help you. You can try the following code but not JavaScript.
System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");
This config solved same error on Wordpress at Azure Services. Thanks.
– Andre Mesquita
May 22 '17 at 13:41
8
I would suggest using a specific origin value to avoid requests from external domains. So for example instead of*
usehttps://www.myotherdomain.com
– pechar
Jun 9 '17 at 8:30
add a comment |
Try XDomain,
Summary: A pure JavaScript CORS alternative/polyfill. No server configuration required - just add a proxy.html on the domain you wish to communicate with. This library uses XHook to hook all XHR, so XDomain should work in conjunction with any library.
add a comment |
If you do NOT want to:
- Disable web security in Chrome
- Use JSONP
- Use a third party site to re-route your requests
and you are sure that your server has CORS enabled then (test CORS here: http://www.test-cors.org/)
Then you need to pass in origin parameter with your request.
This origin MUST match the origin that your browser sends with your request.
You can see it in action here:
http://www.wikinomad.com/app/detail/Campgrounds/3591
The edit functionality sends a GET & POST request to a different domain for fetching data. I set the origin parameter which resolves the issue.
The backend is a mediaWiki engine.
tldr: Add "origin" parameter to your calls which must be the Origin parameter that your browser sends (you cannot spoof the origin parameter)
1
Are your referring to this example code from main.min.js?:t.post("https://wiki.wikinomad.com/api.php?origin=https://www.wikinomad.com", n, o).then(function(e) {...
. If so, isn't it true that this way of specifying an origin requires that the PHP being served from the "backend" is coded to support it, and this answer will not work otherwise?
– CODE-REaD
Feb 15 '18 at 20:18
1
@CODE-REaD, yes that's correct that the backend needs to support CORS as well.
– Ganesh Krishnan
Jan 19 at 17:55
add a comment |
I had a problem with this when I used AngularJS to access my API. The same request worked in SoapUI 5.0 and ColdFusion. My GET method already had Access-Control-Allow-Origin header.
I found out that AngularJS makes a "trial" OPTIONS request. ColdFusion, by default, generates OPTIONS method, but it doesn’t have much, these headers specifically. The error was generated in response to that OPTIONS call, and not to my intentional call to GET. After I added OPTIONS method below to my API, the problem has been resolved.
<cffunction name="optionsMethod" access="remote" output="false" returntype="any" httpmethod="OPTIONS" description="Method to respond to AngularJS trial call">
<cfheader name="Access-Control-Allow-Headers" value="Content-Type,x-requested-with,Authorization,Access-Control-Allow-Origin">
<cfheader name="Access-Control-Allow-Methods" value="GET,OPTIONS">
<cfheader name="Access-Control-Allow-Origin" value="*">
<cfheader name="Access-Control-Max-Age" value="360">
</cffunction>
5
It's not angular that makes the OPTIONS request, it's the browser based on the request!
– Narretz
Oct 12 '15 at 17:36
1
Narretz - calling API via browser doesn't produce this error, nor it makes an extra options call. When angular used it does.
– Leonid Alzhin
Nov 17 '15 at 0:20
3
Narretz is right, it is not related to angular. It's related to how CORS works.
– Emile Bergeron
Oct 18 '16 at 15:23
add a comment |
I had the following configuration, resulting in the same error, when requesting responses from the server.
Server-side: SparkJava --> provides the REST-API
Client-side: ExtJs6 --> provides Browser rendering
On the server-side I had to add this to the response:
Spark.get("/someRestCallToSpark", (req, res) -> {
res.header("Access-Control-Allow-Origin", "*"); //important, otherwise its not working
return "some text";
});
On the client-side I had to add this to the request:
Ext.Ajax.request({
url: "http://localhost:4567/someRestCallToSpark",
useDefaultXhrHeader: false, //important, otherwise its not working
success: function(response, opts) {console.log("success")},
failure: function(response, opts) {console.log("failure")}
});
Had the same architecture, therefore the same problem, and this solve it.
– Fafhrd
Oct 7 '15 at 19:03
3
This is not a good idea to allow requests from any domain. You should restrict it to trusted domain only.
– MD. Sahib Bin Mahboob
Jan 15 '16 at 5:36
If you are the host of both domains, then it is common practice to enable this type of requests.
– kiltek
May 25 '16 at 8:42
add a comment |
Based on shruti's answer, I've created a shortcut of Chrome browser with needed arguments:
69
Excellent. Now I have to go around to my 100,000 users and disable their web security on chrome.
– Ganesh Krishnan
Jul 6 '16 at 6:08
7
@GaneshKrishnan The questioner seems to be a developer and his question (in my opinion) seems for development purposes, as my problem was. And yes, if you want to hack your users, go around them and disable their web security on Chrome :)
– Mohammad AlBanna
Jul 6 '16 at 18:37
add a comment |
https://github.com/Rob--W/cors-anywhere/ provides (Node.js) code you can use to set up and run your own CORS proxy. It’s actively maintained and provides a number of features for controlling the proxy behavior beyond just the basic sending of the correct Access-Control-*
response headers.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has details to explain how browsers handle cross-origin requests that client-side web applications make from JavaScript and what headers you must configure sending of by the server the request is made to, if you can.
In the case where a site you need to make a request to and get a response from doesn’t return the Access-Control-Allow-Origin
response header, browsers are always going to block cross-origin requests made to it directly by your client-side JavaScript code from working. And so if the site is not one you control and can configure behavior for, the only thing that will work in that case is proxying the requests—either through your own proxy you run yourself or through an open proxy.
As mentioned in other comments here, there are good reasons for not trusting an open proxy with your requests. That said, if you know what you’re doing and you decide an open proxy works for your needs, https://cors-anywhere.herokuapp.com/ is one that’s reliably available, actively maintained, and that runs an instance of the https://github.com/Rob--W/cors-anywhere/ code.
As with other open proxies mentioned here (a couple of which at least don’t seem to be available any longer), the way it works is that instead of having your client code send a request directly to, e.g., http://foo.com
you send it to https://cors-anywhere.herokuapp.com/http://foo.com
and the proxy adds the necessary Access-Control-*
headers to the response the browser sees.
add a comment |
You can bypass the problem by using YQL to proxy the request through Yahoo's servers. It is just a few lines of code:
var yql_url = 'https://query.yahooapis.com/v1/public/yql';
var url = 'your api url';
$.ajax({
'url': yql_url,
'data': {
'q': 'SELECT * FROM json WHERE url="'+url+'"',
'format': 'json',
'jsonCompat': 'new',
},
'dataType': 'jsonp',
'success': function(response) {
console.log(response);
},
});
Here's the link with an explanation: https://vverma.net/fetch-any-json-using-jsonp-and-yql.html
but after seconds ... all the other codes run then it initialize.
– saber tabatabaee yazdi
Jun 8 '17 at 16:16
add a comment |
If you are using Entity Framework, it seems that this error will sometimes be thrown even if you have CORS
enabled. I figured out that the error occurred because of a missing finalization of the query. I'm hoping this will help others in the same situation.
The following code can throw the XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource.
error:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
});
}
To fix it, a finalization call like .ToList()
or .FirstOrDefault()
at the end of the query is required, like so:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
}).ToList();
}
1
That seems like just an error that will happen in any application of entity framework if you don't finalize the query. Not really related to CORS or the OP's question.
– Gary
Jan 4 '16 at 21:20
2
It may very well not be related to CORS, but it throws an error that sounds like it has something to do with CORS; hence my answer.
– Loyalar
Feb 17 '16 at 6:52
add a comment |
In my case I was using JEE7 JAX-RS application and following tricks worked perfectly for me:
@GET
@Path("{id}")
public Response getEventData(@PathParam("id") String id) throws FileNotFoundException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/eventdata/" + id + ".json");
JsonReader jsonReader = Json.createReader(inputStream);
return Response.ok(jsonReader.readObject()).header("Access-Control-Allow-Origin", "*").build();
}
add a comment |
I was successfully able to solve (in my case for fonts) using htaccess but obviously, OP is asking little different. But you can use FileMatch pattern and add any sort of extension so that it won't give cros error.
<IfModule mod_headers.c>
<FilesMatch ".(ttf|ttc|otf|eot|woff|woff2|font.css|css)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
https://httpd.apache.org/docs/2.4/mod/core.html#filesmatch
add a comment |
Popular question -- Another thing to look at if you've read this far and nothing else has helped. If you have a CDN such as Akamai, Limelight or similar, you might want to check the cache key you have for the URI of the resource. If it does not include the Origin header value you may be returning a response cached when requested from another Origin. We just spent half a day debugging this. The CDN configuration was updated to only include the Origin value for a few select domains that are ours and set it to null for all others. This seems to work and allows browsers from our known domains to view our resources. Certainly all the other answers are prerequisites to getting here but if the CDN is the first hop from your browser this is something to review.
In our case we could see some requests making it to our service but not nearly the volume the site was sending. That pointed us to the CDN. We were able to go back and see the original request was served from a direct request, not part of a browser AJAX call and the response header Access-Control-Allow-Origin was not included. Apparently the CDN cached this value. The Akamai CDN configuration tweak to consider the Origin request header value as part of the match seems to have made it work for us.
1
In your case, wouldn’t sending theVary: Origin
response header have achieved the same effect? stackoverflow.com/questions/46063304/…
– sideshowbarker
Sep 7 '17 at 21:19
2
Yes but we don't. A service exposed to the world can be DOS'ed via cache explosion by sending bogus values. Akamai has some help in this area to reduce DOS exposure. My point is that you can do everything listed and still have a problem because of caching.
– No Refunds No Returns
Sep 7 '17 at 22:42
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:39
@Quentin You are so RIGHT! however this is the #1 hit for many searches on this topic, there are already a variety of answers that vary from the exact question yet provide useful information AND this was what we discovered on Sept 7 after exhausting all of the threads. I appreciate your downvote. Future readers will be also able be able to weigh whether or not this "not an answer" was helpful by voting, perhaps even differently from you. There is at least one other person who has already publicly disagreed with your opinion. Will be interesting to see how the voting goes from here........
– No Refunds No Returns
Sep 13 '17 at 14:54
+5/-1 Thanks again masses.
– No Refunds No Returns
Aug 21 '18 at 17:42
add a comment |
For the GoLang API:
First you can take a look at MDN CORS Doc to know what CORS is. As far as I know, CORS is about whether to allow Origin Of Request to access Server Resource or not.
And you can restrict which request origin can access the server by setting Access-Control-Allow-Origin
at Header
of Server Response.
For example, Setting following header in Server Response means that only request sent from http://foo.example
can access your server:
Access-Control-Allow-Origin: http://foo.example
and following allow request sent from any origin(or domain):
Access-Control-Allow-Origin: *
And as I know in the error message, requested resource
means resource of server, so No 'Access-Control-Allow-Origin' header is present on the requested resource.
means you didn't set Access-Control-Allow-Origin
header in your Server Response, or maybe you set but the origin of request isn't list in Access-Control-Allow-Origin
so request is not allowed access:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
In GoLang, I use gorilla/mux
package to build API server at localhost:9091
, and I allow CORS by add "Access-Control-Allow-Origin", "*"
to header of response:
func main() { // API Server Code
router := mux.NewRouter()
// API route is /people,
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeople).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))
}
// Method of '/people' route
func GetPeople(w http.ResponseWriter, r *http.Request) {
// Allow CORS by setting * in sever response
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
json.NewEncoder(w).Encode("OKOK")
}
And I use JavaScript in the client, at localhost:9092
make request by Chrome can succesfully get "OKOK" from Server localhost:9091
.
function GetPeople() {
try {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:9091/people", false);
xhttp.setRequestHeader("Content-type", "text/html");
xhttp.send();
var response = JSON.parse(xhttp.response);
alert(xhttp.response);
}
catch (error) {
alert(error.message);
}
}
Besides you can check your request/response header by tools like Fiddler
.
add a comment |
If you get this error message from the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:
<?php header('Access-Control-Allow-Origin: *'); ?>
You really need, especially if you only use JavaScript to do the Ajax request, an internal proxy who takes your query and sends it through to the remote server.
First in your JavaScript code, do an Ajax call to your own server, something like:
$.ajax({
url: yourserver.com/controller/proxy.php,
async: false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:
if (isset($_POST)) {
$apiKey = $_POST['apiKey'];
$cid = $_POST['cid'];
$minorRev = 99;
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;
echo json_encode(file_get_contents($url));
}
By doing:
echo json_encode(file_get_contents($url));
You are just doing the same query, but on the server side and after that, it should work fine.
Answer copied and pasted from NizarBsb
@NizarBsb's answer link is here No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
– tech_me
Jun 6 '18 at 13:04
This is a big security risk!
– Stephan Weinhold
Jun 9 '18 at 20:14
@stephan-weinhold in case you would actually sanitize the url parameters. would it still be a security risk? why?
– mwallisch
Jun 13 '18 at 11:15
add a comment |
A lot of times this happens to me from javascript to my php api, because one of a few reasons.
I forget to put the <?php header('Access-Control-Allow-Origin: *'); ?
is one. This is helpful for cross sub domain access. Another reason, is because in jQuery ajax request I am specifying a specific dataType and returning a different dataType, so it throws an error.
The Last and most prominent reasoning for this error is there is a parse error on the page you are requesting. If you hit that page url in your browser than more than likely you will see a parse error and you will have a line number to address the issue.
I hope this helps someone. It took me a while each time to debug this and I wish I had a checklist of things to verify.
add a comment |
I got this error with $http.get
in Angular. I needed to use $http.jsonp
instead.
add a comment |
On my website (based on .NET) I've just added this:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Big thanks to this video.
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
CORS is for you.
CORS is "Cross Origin Resource Sharing" and is a way to send a cross-domain request. Now the XMLHttpRequest2 and Fetch API both support CORS.
But it has its limits. Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.
And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*').
For lots of request way if you don't know what to choose, I think you need a fully functional component to do that. Let me introduce a simple component catta
If you are using a modern browser (> Internet Explorer9, Chrome, Firefox, Edge, etc.), it is very recommended you use a simple, but beautiful component, https://github.com/Joker-Jelly/catta. It has no dependencies, is less than 3 KB, and it supports Fetch, Ajax and JSONP with same dead-simple syntax and options.
catta('./data/simple.json').then(function (res) {
console.log(res);
});
It also supports all the way to import to your project, like ES6 module, CommonJS and even <script>
in HTML.
I have an IIS site which is local that is hosting my API. I have an external site which is accessed outside the local network. I am trying to execute the API from the external site, I have CORS enabled for the external site (e.g.[EnableCors(origins: "http://websitelink.com", headers: "*", methods: "*")]
but it is not working. Any idea? forums.asp.net/p/2117965/…
– Si8
Mar 24 '17 at 14:12
add a comment |
Most of these answers tell users how to add CORS headers to a server they control.
However, if you need data from a server you don't control in a webpage, one solution is to create a script tag on your page, set the src attribute to the api endpoint that doesn't have CORS headers, then load that data onto the page:
window.handleData = function(data) {
console.log(data)
};
var script = document.createElement('script');
script.setAttribute('src','https://some.api/without/cors/headers.com&callback=handleData');
document.body.appendChild(script);
Excellent answer, but if script is not in correct format, then you can't reach its code (script.text= empty). What to do in this case? How to reach its code?
– Angel T
Feb 8 '18 at 6:52
How to prevent the execution of the script (maybe as comment it all)?
– Angel T
Feb 8 '18 at 7:16
And another interesting thing: Only IE11 with Enabled "Access data sources across domains" can access cross-domain (without of need to control server to modificate Origin!. All rest major browsers can't
– Angel T
Feb 8 '18 at 8:14
add a comment |
For completeness, Apache allows cors:
Header set Access-Control-Allow-Origin "http://www.allowonlyfromthisurl.com"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, Accept-Encoding, Accept-Language, Cookie, Referer"
Anybody can add to that ^
– zak
Nov 20 '17 at 0:05
Worked for Apache and laravel 5.4
– Rohit Dhiman
Sep 18 '18 at 6:56
add a comment |
In jsonp request you should catch "jsonpCallback" and send him back.
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
On backend side (if you use as backend PHP)
echo $_GET['callback'].'({"ip":"192.168.1.1"})';
In this case backend response seems like
jQuery331009526199802841284_1533646326884({"ip":"192.168.1.1"})
but you can set a "jsonpCallback" manually on frontend and catch him on backend side
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'get_ip',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
In this case backend response seems like
get_ip({"ip":"192.168.1.1"})
add a comment |
in case you want to fix this on the backend (in Flask), rather than on the front end, I would totally recommend the Flask CORS python package. Flask Cors
With one simple line in your app.py you can automatically insert the standard allow any origin header, or customise it as required.
add a comment |
For Ruby on Rails server in application_controller.rb
, add this:
after_action :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
end
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
1 2
next
protected by Community♦ Apr 17 '15 at 16:02
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
41 Answers
41
active
oldest
votes
41 Answers
41
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
5
You're right. I doing request to different domain than my page is. API is on server and I run request from localhost. Before I accept answer can you explain me what mean "executing the request directly" ? POSTMAN don't use domain?
– Mr Jedi
Nov 17 '13 at 19:54
144
The browser is not blocking the request. The only browsers that outright block cross-origin ajax requests is IE7 or older. All browsers, other than IE7 and older, implement the CORS spec (IE8 & IE9 partially). All you need to do is opt-in to CORS requests on your API server by returning the proper headers based on the request. You should read up on CORS concepts at mzl.la/VOFrSz. Postman sends requests via XHR as well. If you are not seeing the same problem when using postman, this means that you are unknowingly not sending the same request via postman.
– Ray Nicholus
Nov 17 '13 at 20:01
8
@MD.SahibBinMahboob Postman is NOT sending a request "from your java/python" code. It is sending the request directly from the browser. XHR in Chrome extensions does work a bit differently, especially when cross-origin requests are involved.
– Ray Nicholus
Nov 17 '13 at 20:08
9
@yves it's the browser who actually imposed the rule. So initiating request from any places rather than browser should work file
– MD. Sahib Bin Mahboob
Aug 5 '15 at 12:54
1
@SuhailGupta, if you allow origins in your server, it will be allowed to do the request which is actually known as CORS.
– MD. Sahib Bin Mahboob
Feb 29 '16 at 5:07
|
show 9 more comments
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
5
You're right. I doing request to different domain than my page is. API is on server and I run request from localhost. Before I accept answer can you explain me what mean "executing the request directly" ? POSTMAN don't use domain?
– Mr Jedi
Nov 17 '13 at 19:54
144
The browser is not blocking the request. The only browsers that outright block cross-origin ajax requests is IE7 or older. All browsers, other than IE7 and older, implement the CORS spec (IE8 & IE9 partially). All you need to do is opt-in to CORS requests on your API server by returning the proper headers based on the request. You should read up on CORS concepts at mzl.la/VOFrSz. Postman sends requests via XHR as well. If you are not seeing the same problem when using postman, this means that you are unknowingly not sending the same request via postman.
– Ray Nicholus
Nov 17 '13 at 20:01
8
@MD.SahibBinMahboob Postman is NOT sending a request "from your java/python" code. It is sending the request directly from the browser. XHR in Chrome extensions does work a bit differently, especially when cross-origin requests are involved.
– Ray Nicholus
Nov 17 '13 at 20:08
9
@yves it's the browser who actually imposed the rule. So initiating request from any places rather than browser should work file
– MD. Sahib Bin Mahboob
Aug 5 '15 at 12:54
1
@SuhailGupta, if you allow origins in your server, it will be allowed to do the request which is actually known as CORS.
– MD. Sahib Bin Mahboob
Feb 29 '16 at 5:07
|
show 9 more comments
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
edited Jan 23 '14 at 0:46
Peter Mortensen
13.8k1987113
13.8k1987113
answered Nov 17 '13 at 19:49
MD. Sahib Bin MahboobMD. Sahib Bin Mahboob
14.6k21845
14.6k21845
5
You're right. I doing request to different domain than my page is. API is on server and I run request from localhost. Before I accept answer can you explain me what mean "executing the request directly" ? POSTMAN don't use domain?
– Mr Jedi
Nov 17 '13 at 19:54
144
The browser is not blocking the request. The only browsers that outright block cross-origin ajax requests is IE7 or older. All browsers, other than IE7 and older, implement the CORS spec (IE8 & IE9 partially). All you need to do is opt-in to CORS requests on your API server by returning the proper headers based on the request. You should read up on CORS concepts at mzl.la/VOFrSz. Postman sends requests via XHR as well. If you are not seeing the same problem when using postman, this means that you are unknowingly not sending the same request via postman.
– Ray Nicholus
Nov 17 '13 at 20:01
8
@MD.SahibBinMahboob Postman is NOT sending a request "from your java/python" code. It is sending the request directly from the browser. XHR in Chrome extensions does work a bit differently, especially when cross-origin requests are involved.
– Ray Nicholus
Nov 17 '13 at 20:08
9
@yves it's the browser who actually imposed the rule. So initiating request from any places rather than browser should work file
– MD. Sahib Bin Mahboob
Aug 5 '15 at 12:54
1
@SuhailGupta, if you allow origins in your server, it will be allowed to do the request which is actually known as CORS.
– MD. Sahib Bin Mahboob
Feb 29 '16 at 5:07
|
show 9 more comments
5
You're right. I doing request to different domain than my page is. API is on server and I run request from localhost. Before I accept answer can you explain me what mean "executing the request directly" ? POSTMAN don't use domain?
– Mr Jedi
Nov 17 '13 at 19:54
144
The browser is not blocking the request. The only browsers that outright block cross-origin ajax requests is IE7 or older. All browsers, other than IE7 and older, implement the CORS spec (IE8 & IE9 partially). All you need to do is opt-in to CORS requests on your API server by returning the proper headers based on the request. You should read up on CORS concepts at mzl.la/VOFrSz. Postman sends requests via XHR as well. If you are not seeing the same problem when using postman, this means that you are unknowingly not sending the same request via postman.
– Ray Nicholus
Nov 17 '13 at 20:01
8
@MD.SahibBinMahboob Postman is NOT sending a request "from your java/python" code. It is sending the request directly from the browser. XHR in Chrome extensions does work a bit differently, especially when cross-origin requests are involved.
– Ray Nicholus
Nov 17 '13 at 20:08
9
@yves it's the browser who actually imposed the rule. So initiating request from any places rather than browser should work file
– MD. Sahib Bin Mahboob
Aug 5 '15 at 12:54
1
@SuhailGupta, if you allow origins in your server, it will be allowed to do the request which is actually known as CORS.
– MD. Sahib Bin Mahboob
Feb 29 '16 at 5:07
5
5
You're right. I doing request to different domain than my page is. API is on server and I run request from localhost. Before I accept answer can you explain me what mean "executing the request directly" ? POSTMAN don't use domain?
– Mr Jedi
Nov 17 '13 at 19:54
You're right. I doing request to different domain than my page is. API is on server and I run request from localhost. Before I accept answer can you explain me what mean "executing the request directly" ? POSTMAN don't use domain?
– Mr Jedi
Nov 17 '13 at 19:54
144
144
The browser is not blocking the request. The only browsers that outright block cross-origin ajax requests is IE7 or older. All browsers, other than IE7 and older, implement the CORS spec (IE8 & IE9 partially). All you need to do is opt-in to CORS requests on your API server by returning the proper headers based on the request. You should read up on CORS concepts at mzl.la/VOFrSz. Postman sends requests via XHR as well. If you are not seeing the same problem when using postman, this means that you are unknowingly not sending the same request via postman.
– Ray Nicholus
Nov 17 '13 at 20:01
The browser is not blocking the request. The only browsers that outright block cross-origin ajax requests is IE7 or older. All browsers, other than IE7 and older, implement the CORS spec (IE8 & IE9 partially). All you need to do is opt-in to CORS requests on your API server by returning the proper headers based on the request. You should read up on CORS concepts at mzl.la/VOFrSz. Postman sends requests via XHR as well. If you are not seeing the same problem when using postman, this means that you are unknowingly not sending the same request via postman.
– Ray Nicholus
Nov 17 '13 at 20:01
8
8
@MD.SahibBinMahboob Postman is NOT sending a request "from your java/python" code. It is sending the request directly from the browser. XHR in Chrome extensions does work a bit differently, especially when cross-origin requests are involved.
– Ray Nicholus
Nov 17 '13 at 20:08
@MD.SahibBinMahboob Postman is NOT sending a request "from your java/python" code. It is sending the request directly from the browser. XHR in Chrome extensions does work a bit differently, especially when cross-origin requests are involved.
– Ray Nicholus
Nov 17 '13 at 20:08
9
9
@yves it's the browser who actually imposed the rule. So initiating request from any places rather than browser should work file
– MD. Sahib Bin Mahboob
Aug 5 '15 at 12:54
@yves it's the browser who actually imposed the rule. So initiating request from any places rather than browser should work file
– MD. Sahib Bin Mahboob
Aug 5 '15 at 12:54
1
1
@SuhailGupta, if you allow origins in your server, it will be allowed to do the request which is actually known as CORS.
– MD. Sahib Bin Mahboob
Feb 29 '16 at 5:07
@SuhailGupta, if you allow origins in your server, it will be allowed to do the request which is actually known as CORS.
– MD. Sahib Bin Mahboob
Feb 29 '16 at 5:07
|
show 9 more comments
This is not a fix for production or when application has to be shown to the client, this is only helpful when UI and Backend development are on different servers and in production they are actually on same server. For example: While developing UI for any application if there is a need to test it locally pointing it to backend server, in that scenario this is the perfect fix. For production fix, CORS headers has to be added to the backend server to allow cross origin access.
The easy way is to just add the extension in google chrome to allow access using CORS.
(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)
Just enable this extension whenever you want allow access to no 'access-control-allow-origin' header request.
Or
In Windows, paste this command in run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
this will open a new chrome browser which allow access to no 'access-control-allow-origin' header request.
137
This is great but clients can't be asked to launch chrome this way to enforce an internal requirement for a webservice call.
– Taersious
Sep 24 '15 at 17:55
78
this shouldn't be accepted as an answer, installing a third party plugin to fix your app, rather than understanding CORS and fixing your app, how will other people use your api? will you make them all install this plugin
– James Kirkby
Apr 28 '16 at 11:10
4
I installed this extension and did a request, than checked the request in fiddler, the following was specified -> Origin: evil.com . Looks like this extension is changing the Origin to evil.com
– wagwanJahMan
May 10 '16 at 12:54
14
I think this is a really great answer if you don't need a permanent fix or if you only need CORS disabled temporarily. That's what I needed, and this solution worked great. Obviously, this could never be considered a permanent solution.
– jtcotton63
Mar 24 '17 at 0:44
2
This answer is fine. For dev work, this got me up-and-running asap and I will come back and find the proper fix later...
– Adam Hughes
Oct 19 '17 at 19:48
|
show 14 more comments
This is not a fix for production or when application has to be shown to the client, this is only helpful when UI and Backend development are on different servers and in production they are actually on same server. For example: While developing UI for any application if there is a need to test it locally pointing it to backend server, in that scenario this is the perfect fix. For production fix, CORS headers has to be added to the backend server to allow cross origin access.
The easy way is to just add the extension in google chrome to allow access using CORS.
(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)
Just enable this extension whenever you want allow access to no 'access-control-allow-origin' header request.
Or
In Windows, paste this command in run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
this will open a new chrome browser which allow access to no 'access-control-allow-origin' header request.
137
This is great but clients can't be asked to launch chrome this way to enforce an internal requirement for a webservice call.
– Taersious
Sep 24 '15 at 17:55
78
this shouldn't be accepted as an answer, installing a third party plugin to fix your app, rather than understanding CORS and fixing your app, how will other people use your api? will you make them all install this plugin
– James Kirkby
Apr 28 '16 at 11:10
4
I installed this extension and did a request, than checked the request in fiddler, the following was specified -> Origin: evil.com . Looks like this extension is changing the Origin to evil.com
– wagwanJahMan
May 10 '16 at 12:54
14
I think this is a really great answer if you don't need a permanent fix or if you only need CORS disabled temporarily. That's what I needed, and this solution worked great. Obviously, this could never be considered a permanent solution.
– jtcotton63
Mar 24 '17 at 0:44
2
This answer is fine. For dev work, this got me up-and-running asap and I will come back and find the proper fix later...
– Adam Hughes
Oct 19 '17 at 19:48
|
show 14 more comments
This is not a fix for production or when application has to be shown to the client, this is only helpful when UI and Backend development are on different servers and in production they are actually on same server. For example: While developing UI for any application if there is a need to test it locally pointing it to backend server, in that scenario this is the perfect fix. For production fix, CORS headers has to be added to the backend server to allow cross origin access.
The easy way is to just add the extension in google chrome to allow access using CORS.
(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)
Just enable this extension whenever you want allow access to no 'access-control-allow-origin' header request.
Or
In Windows, paste this command in run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
this will open a new chrome browser which allow access to no 'access-control-allow-origin' header request.
This is not a fix for production or when application has to be shown to the client, this is only helpful when UI and Backend development are on different servers and in production they are actually on same server. For example: While developing UI for any application if there is a need to test it locally pointing it to backend server, in that scenario this is the perfect fix. For production fix, CORS headers has to be added to the backend server to allow cross origin access.
The easy way is to just add the extension in google chrome to allow access using CORS.
(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)
Just enable this extension whenever you want allow access to no 'access-control-allow-origin' header request.
Or
In Windows, paste this command in run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
this will open a new chrome browser which allow access to no 'access-control-allow-origin' header request.
edited Sep 14 '16 at 4:41
answered Mar 4 '15 at 6:42
shrutishruti
5,51811011
5,51811011
137
This is great but clients can't be asked to launch chrome this way to enforce an internal requirement for a webservice call.
– Taersious
Sep 24 '15 at 17:55
78
this shouldn't be accepted as an answer, installing a third party plugin to fix your app, rather than understanding CORS and fixing your app, how will other people use your api? will you make them all install this plugin
– James Kirkby
Apr 28 '16 at 11:10
4
I installed this extension and did a request, than checked the request in fiddler, the following was specified -> Origin: evil.com . Looks like this extension is changing the Origin to evil.com
– wagwanJahMan
May 10 '16 at 12:54
14
I think this is a really great answer if you don't need a permanent fix or if you only need CORS disabled temporarily. That's what I needed, and this solution worked great. Obviously, this could never be considered a permanent solution.
– jtcotton63
Mar 24 '17 at 0:44
2
This answer is fine. For dev work, this got me up-and-running asap and I will come back and find the proper fix later...
– Adam Hughes
Oct 19 '17 at 19:48
|
show 14 more comments
137
This is great but clients can't be asked to launch chrome this way to enforce an internal requirement for a webservice call.
– Taersious
Sep 24 '15 at 17:55
78
this shouldn't be accepted as an answer, installing a third party plugin to fix your app, rather than understanding CORS and fixing your app, how will other people use your api? will you make them all install this plugin
– James Kirkby
Apr 28 '16 at 11:10
4
I installed this extension and did a request, than checked the request in fiddler, the following was specified -> Origin: evil.com . Looks like this extension is changing the Origin to evil.com
– wagwanJahMan
May 10 '16 at 12:54
14
I think this is a really great answer if you don't need a permanent fix or if you only need CORS disabled temporarily. That's what I needed, and this solution worked great. Obviously, this could never be considered a permanent solution.
– jtcotton63
Mar 24 '17 at 0:44
2
This answer is fine. For dev work, this got me up-and-running asap and I will come back and find the proper fix later...
– Adam Hughes
Oct 19 '17 at 19:48
137
137
This is great but clients can't be asked to launch chrome this way to enforce an internal requirement for a webservice call.
– Taersious
Sep 24 '15 at 17:55
This is great but clients can't be asked to launch chrome this way to enforce an internal requirement for a webservice call.
– Taersious
Sep 24 '15 at 17:55
78
78
this shouldn't be accepted as an answer, installing a third party plugin to fix your app, rather than understanding CORS and fixing your app, how will other people use your api? will you make them all install this plugin
– James Kirkby
Apr 28 '16 at 11:10
this shouldn't be accepted as an answer, installing a third party plugin to fix your app, rather than understanding CORS and fixing your app, how will other people use your api? will you make them all install this plugin
– James Kirkby
Apr 28 '16 at 11:10
4
4
I installed this extension and did a request, than checked the request in fiddler, the following was specified -> Origin: evil.com . Looks like this extension is changing the Origin to evil.com
– wagwanJahMan
May 10 '16 at 12:54
I installed this extension and did a request, than checked the request in fiddler, the following was specified -> Origin: evil.com . Looks like this extension is changing the Origin to evil.com
– wagwanJahMan
May 10 '16 at 12:54
14
14
I think this is a really great answer if you don't need a permanent fix or if you only need CORS disabled temporarily. That's what I needed, and this solution worked great. Obviously, this could never be considered a permanent solution.
– jtcotton63
Mar 24 '17 at 0:44
I think this is a really great answer if you don't need a permanent fix or if you only need CORS disabled temporarily. That's what I needed, and this solution worked great. Obviously, this could never be considered a permanent solution.
– jtcotton63
Mar 24 '17 at 0:44
2
2
This answer is fine. For dev work, this got me up-and-running asap and I will come back and find the proper fix later...
– Adam Hughes
Oct 19 '17 at 19:48
This answer is fine. For dev work, this got me up-and-running asap and I will come back and find the proper fix later...
– Adam Hughes
Oct 19 '17 at 19:48
|
show 14 more comments
If you can deal with JSON in return, then try using JSONP (note the P at the end) for speaking between domains:
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ......
Learn more about working with JSONP here:
The advent of JSONP — essentially a consensual cross-site scripting hack — has opened the door to powerful mashups of content. Many prominent sites provide JSONP services, allowing you access to their content via a predefined API.
2
With NodeJs with datatype json worked, with ASP.Net this was the culprit
– Gaizka Allende
May 15 '14 at 9:36
84
Be aware jsonp doesn't work for POST content. More discussions here.
– Prabu Raja
Nov 13 '14 at 0:28
61
How does this have so many up votes when you cant use jsonp with POST requests?!?!
– fatlog
Aug 7 '15 at 15:06
8
When you useJSONP
, $.ajax will ignoretype
, so it's alwaysGET
which means this answer will always work.
– noob
Oct 6 '16 at 3:56
8
Also note that JSONP is not directly interchangeable with JSON. You need the server to return data in JSONP format too. Simply changing thedataType
in the AJAX request settings alone isn't going to work.
– Rory McCrossan
Sep 7 '17 at 10:19
|
show 4 more comments
If you can deal with JSON in return, then try using JSONP (note the P at the end) for speaking between domains:
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ......
Learn more about working with JSONP here:
The advent of JSONP — essentially a consensual cross-site scripting hack — has opened the door to powerful mashups of content. Many prominent sites provide JSONP services, allowing you access to their content via a predefined API.
2
With NodeJs with datatype json worked, with ASP.Net this was the culprit
– Gaizka Allende
May 15 '14 at 9:36
84
Be aware jsonp doesn't work for POST content. More discussions here.
– Prabu Raja
Nov 13 '14 at 0:28
61
How does this have so many up votes when you cant use jsonp with POST requests?!?!
– fatlog
Aug 7 '15 at 15:06
8
When you useJSONP
, $.ajax will ignoretype
, so it's alwaysGET
which means this answer will always work.
– noob
Oct 6 '16 at 3:56
8
Also note that JSONP is not directly interchangeable with JSON. You need the server to return data in JSONP format too. Simply changing thedataType
in the AJAX request settings alone isn't going to work.
– Rory McCrossan
Sep 7 '17 at 10:19
|
show 4 more comments
If you can deal with JSON in return, then try using JSONP (note the P at the end) for speaking between domains:
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ......
Learn more about working with JSONP here:
The advent of JSONP — essentially a consensual cross-site scripting hack — has opened the door to powerful mashups of content. Many prominent sites provide JSONP services, allowing you access to their content via a predefined API.
If you can deal with JSON in return, then try using JSONP (note the P at the end) for speaking between domains:
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ......
Learn more about working with JSONP here:
The advent of JSONP — essentially a consensual cross-site scripting hack — has opened the door to powerful mashups of content. Many prominent sites provide JSONP services, allowing you access to their content via a predefined API.
edited Jul 13 '17 at 18:14
Hristiyan Dodov
1,80411426
1,80411426
answered Feb 22 '14 at 0:42
GavinGavin
3,687185
3,687185
2
With NodeJs with datatype json worked, with ASP.Net this was the culprit
– Gaizka Allende
May 15 '14 at 9:36
84
Be aware jsonp doesn't work for POST content. More discussions here.
– Prabu Raja
Nov 13 '14 at 0:28
61
How does this have so many up votes when you cant use jsonp with POST requests?!?!
– fatlog
Aug 7 '15 at 15:06
8
When you useJSONP
, $.ajax will ignoretype
, so it's alwaysGET
which means this answer will always work.
– noob
Oct 6 '16 at 3:56
8
Also note that JSONP is not directly interchangeable with JSON. You need the server to return data in JSONP format too. Simply changing thedataType
in the AJAX request settings alone isn't going to work.
– Rory McCrossan
Sep 7 '17 at 10:19
|
show 4 more comments
2
With NodeJs with datatype json worked, with ASP.Net this was the culprit
– Gaizka Allende
May 15 '14 at 9:36
84
Be aware jsonp doesn't work for POST content. More discussions here.
– Prabu Raja
Nov 13 '14 at 0:28
61
How does this have so many up votes when you cant use jsonp with POST requests?!?!
– fatlog
Aug 7 '15 at 15:06
8
When you useJSONP
, $.ajax will ignoretype
, so it's alwaysGET
which means this answer will always work.
– noob
Oct 6 '16 at 3:56
8
Also note that JSONP is not directly interchangeable with JSON. You need the server to return data in JSONP format too. Simply changing thedataType
in the AJAX request settings alone isn't going to work.
– Rory McCrossan
Sep 7 '17 at 10:19
2
2
With NodeJs with datatype json worked, with ASP.Net this was the culprit
– Gaizka Allende
May 15 '14 at 9:36
With NodeJs with datatype json worked, with ASP.Net this was the culprit
– Gaizka Allende
May 15 '14 at 9:36
84
84
Be aware jsonp doesn't work for POST content. More discussions here.
– Prabu Raja
Nov 13 '14 at 0:28
Be aware jsonp doesn't work for POST content. More discussions here.
– Prabu Raja
Nov 13 '14 at 0:28
61
61
How does this have so many up votes when you cant use jsonp with POST requests?!?!
– fatlog
Aug 7 '15 at 15:06
How does this have so many up votes when you cant use jsonp with POST requests?!?!
– fatlog
Aug 7 '15 at 15:06
8
8
When you use
JSONP
, $.ajax will ignore type
, so it's always GET
which means this answer will always work.– noob
Oct 6 '16 at 3:56
When you use
JSONP
, $.ajax will ignore type
, so it's always GET
which means this answer will always work.– noob
Oct 6 '16 at 3:56
8
8
Also note that JSONP is not directly interchangeable with JSON. You need the server to return data in JSONP format too. Simply changing the
dataType
in the AJAX request settings alone isn't going to work.– Rory McCrossan
Sep 7 '17 at 10:19
Also note that JSONP is not directly interchangeable with JSON. You need the server to return data in JSONP format too. Simply changing the
dataType
in the AJAX request settings alone isn't going to work.– Rory McCrossan
Sep 7 '17 at 10:19
|
show 4 more comments
It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:
<?php header('Access-Control-Allow-Origin: *'); ?>
Warning: This contains a security issue for your PHP file that it could be called by attackers. you have to use sessions and cookies for authentication to prevent your file/service against this attack. Your service is vulnerable to cross-site request forgery (CSRF).
If you are using Node-red you have to allow CORS in the node-red/settings.js
file by un-commenting the following lines:
// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
origin: "*",
methods: "GET,PUT,POST,DELETE"
},
314
The question was not about PHP at all.
– mknaf
Dec 10 '14 at 14:32
83
and it's not secure
– llazzaro
Dec 20 '14 at 19:25
112
You shouldn't turn off CORS because you don't know what its for. This is a terrible answer.
– meagar♦
Dec 30 '14 at 6:12
105
Even though it might not be secure, the question was not about security, but how to accomplish the task. This is one of the options that a developer has to choose from when dealing with cross-domain AJAX requests. It helped me resolve the issue, and for my application, I don't care where the data came from. I sanitize all the input with PHP on the destination domain, so, if someone wants to post some junk to it, let them try. The main point here is, cross-domain AJAX can be allowed from the destination domain. +1 for the answer.
– ZurabWeb
Feb 26 '15 at 16:37
18
While I agree with the general message Piero is giving, that it's not specifically about security, but security is a concern. I think this should have at least said something like "This is generally bad! Don't do this unless you know what you're doing! Here's more documentation on it: ...", and maybe briefly explain why. I would hate for someone to come on here and just think "Oh, I can just add/adjust this header and I'm good!" and not know the full ramifications. I mean, it's kind of on them to research and all, but still.
– Thomas F.
Oct 15 '15 at 14:55
|
show 9 more comments
It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:
<?php header('Access-Control-Allow-Origin: *'); ?>
Warning: This contains a security issue for your PHP file that it could be called by attackers. you have to use sessions and cookies for authentication to prevent your file/service against this attack. Your service is vulnerable to cross-site request forgery (CSRF).
If you are using Node-red you have to allow CORS in the node-red/settings.js
file by un-commenting the following lines:
// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
origin: "*",
methods: "GET,PUT,POST,DELETE"
},
314
The question was not about PHP at all.
– mknaf
Dec 10 '14 at 14:32
83
and it's not secure
– llazzaro
Dec 20 '14 at 19:25
112
You shouldn't turn off CORS because you don't know what its for. This is a terrible answer.
– meagar♦
Dec 30 '14 at 6:12
105
Even though it might not be secure, the question was not about security, but how to accomplish the task. This is one of the options that a developer has to choose from when dealing with cross-domain AJAX requests. It helped me resolve the issue, and for my application, I don't care where the data came from. I sanitize all the input with PHP on the destination domain, so, if someone wants to post some junk to it, let them try. The main point here is, cross-domain AJAX can be allowed from the destination domain. +1 for the answer.
– ZurabWeb
Feb 26 '15 at 16:37
18
While I agree with the general message Piero is giving, that it's not specifically about security, but security is a concern. I think this should have at least said something like "This is generally bad! Don't do this unless you know what you're doing! Here's more documentation on it: ...", and maybe briefly explain why. I would hate for someone to come on here and just think "Oh, I can just add/adjust this header and I'm good!" and not know the full ramifications. I mean, it's kind of on them to research and all, but still.
– Thomas F.
Oct 15 '15 at 14:55
|
show 9 more comments
It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:
<?php header('Access-Control-Allow-Origin: *'); ?>
Warning: This contains a security issue for your PHP file that it could be called by attackers. you have to use sessions and cookies for authentication to prevent your file/service against this attack. Your service is vulnerable to cross-site request forgery (CSRF).
If you are using Node-red you have to allow CORS in the node-red/settings.js
file by un-commenting the following lines:
// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
origin: "*",
methods: "GET,PUT,POST,DELETE"
},
It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:
<?php header('Access-Control-Allow-Origin: *'); ?>
Warning: This contains a security issue for your PHP file that it could be called by attackers. you have to use sessions and cookies for authentication to prevent your file/service against this attack. Your service is vulnerable to cross-site request forgery (CSRF).
If you are using Node-red you have to allow CORS in the node-red/settings.js
file by un-commenting the following lines:
// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
origin: "*",
methods: "GET,PUT,POST,DELETE"
},
edited Apr 28 '18 at 5:28
mplungjan
89.4k22127184
89.4k22127184
answered Dec 3 '14 at 20:24
shady sherifshady sherif
5,00912524
5,00912524
314
The question was not about PHP at all.
– mknaf
Dec 10 '14 at 14:32
83
and it's not secure
– llazzaro
Dec 20 '14 at 19:25
112
You shouldn't turn off CORS because you don't know what its for. This is a terrible answer.
– meagar♦
Dec 30 '14 at 6:12
105
Even though it might not be secure, the question was not about security, but how to accomplish the task. This is one of the options that a developer has to choose from when dealing with cross-domain AJAX requests. It helped me resolve the issue, and for my application, I don't care where the data came from. I sanitize all the input with PHP on the destination domain, so, if someone wants to post some junk to it, let them try. The main point here is, cross-domain AJAX can be allowed from the destination domain. +1 for the answer.
– ZurabWeb
Feb 26 '15 at 16:37
18
While I agree with the general message Piero is giving, that it's not specifically about security, but security is a concern. I think this should have at least said something like "This is generally bad! Don't do this unless you know what you're doing! Here's more documentation on it: ...", and maybe briefly explain why. I would hate for someone to come on here and just think "Oh, I can just add/adjust this header and I'm good!" and not know the full ramifications. I mean, it's kind of on them to research and all, but still.
– Thomas F.
Oct 15 '15 at 14:55
|
show 9 more comments
314
The question was not about PHP at all.
– mknaf
Dec 10 '14 at 14:32
83
and it's not secure
– llazzaro
Dec 20 '14 at 19:25
112
You shouldn't turn off CORS because you don't know what its for. This is a terrible answer.
– meagar♦
Dec 30 '14 at 6:12
105
Even though it might not be secure, the question was not about security, but how to accomplish the task. This is one of the options that a developer has to choose from when dealing with cross-domain AJAX requests. It helped me resolve the issue, and for my application, I don't care where the data came from. I sanitize all the input with PHP on the destination domain, so, if someone wants to post some junk to it, let them try. The main point here is, cross-domain AJAX can be allowed from the destination domain. +1 for the answer.
– ZurabWeb
Feb 26 '15 at 16:37
18
While I agree with the general message Piero is giving, that it's not specifically about security, but security is a concern. I think this should have at least said something like "This is generally bad! Don't do this unless you know what you're doing! Here's more documentation on it: ...", and maybe briefly explain why. I would hate for someone to come on here and just think "Oh, I can just add/adjust this header and I'm good!" and not know the full ramifications. I mean, it's kind of on them to research and all, but still.
– Thomas F.
Oct 15 '15 at 14:55
314
314
The question was not about PHP at all.
– mknaf
Dec 10 '14 at 14:32
The question was not about PHP at all.
– mknaf
Dec 10 '14 at 14:32
83
83
and it's not secure
– llazzaro
Dec 20 '14 at 19:25
and it's not secure
– llazzaro
Dec 20 '14 at 19:25
112
112
You shouldn't turn off CORS because you don't know what its for. This is a terrible answer.
– meagar♦
Dec 30 '14 at 6:12
You shouldn't turn off CORS because you don't know what its for. This is a terrible answer.
– meagar♦
Dec 30 '14 at 6:12
105
105
Even though it might not be secure, the question was not about security, but how to accomplish the task. This is one of the options that a developer has to choose from when dealing with cross-domain AJAX requests. It helped me resolve the issue, and for my application, I don't care where the data came from. I sanitize all the input with PHP on the destination domain, so, if someone wants to post some junk to it, let them try. The main point here is, cross-domain AJAX can be allowed from the destination domain. +1 for the answer.
– ZurabWeb
Feb 26 '15 at 16:37
Even though it might not be secure, the question was not about security, but how to accomplish the task. This is one of the options that a developer has to choose from when dealing with cross-domain AJAX requests. It helped me resolve the issue, and for my application, I don't care where the data came from. I sanitize all the input with PHP on the destination domain, so, if someone wants to post some junk to it, let them try. The main point here is, cross-domain AJAX can be allowed from the destination domain. +1 for the answer.
– ZurabWeb
Feb 26 '15 at 16:37
18
18
While I agree with the general message Piero is giving, that it's not specifically about security, but security is a concern. I think this should have at least said something like "This is generally bad! Don't do this unless you know what you're doing! Here's more documentation on it: ...", and maybe briefly explain why. I would hate for someone to come on here and just think "Oh, I can just add/adjust this header and I'm good!" and not know the full ramifications. I mean, it's kind of on them to research and all, but still.
– Thomas F.
Oct 15 '15 at 14:55
While I agree with the general message Piero is giving, that it's not specifically about security, but security is a concern. I think this should have at least said something like "This is generally bad! Don't do this unless you know what you're doing! Here's more documentation on it: ...", and maybe briefly explain why. I would hate for someone to come on here and just think "Oh, I can just add/adjust this header and I'm good!" and not know the full ramifications. I mean, it's kind of on them to research and all, but still.
– Thomas F.
Oct 15 '15 at 14:55
|
show 9 more comments
I wish someone shared this site with me long ago http://cors.io/ it would have saved a ton of time compared to building and relying on my own proxy. However, as you move to production, having your own proxy is the best bet since you still control all aspects of your data.
All you need:
https://cors.io/?http://HTTP_YOUR_LINK_HERE
27
What are the downsides of this? Are those guys intercepting my data?
– Sebastialonso
Aug 21 '15 at 16:33
6
cors.io/?u=HTTP_YOUR_LINK_HERE (small correction)
– jkpd
Sep 17 '15 at 13:05
150
I don't think sending your data over 3rd party proxy is a good idea
– Daniel Alexandrov
Oct 16 '15 at 14:07
9
One downside is they are sometimes overloaded, as they are now.This application is temporarily over its serving quota. Please try again later.
– evelynhathaway
Feb 20 '16 at 7:52
17
try toohttps://crossorigin.me/http://example.com
– KingRider
Apr 15 '16 at 15:05
|
show 12 more comments
I wish someone shared this site with me long ago http://cors.io/ it would have saved a ton of time compared to building and relying on my own proxy. However, as you move to production, having your own proxy is the best bet since you still control all aspects of your data.
All you need:
https://cors.io/?http://HTTP_YOUR_LINK_HERE
27
What are the downsides of this? Are those guys intercepting my data?
– Sebastialonso
Aug 21 '15 at 16:33
6
cors.io/?u=HTTP_YOUR_LINK_HERE (small correction)
– jkpd
Sep 17 '15 at 13:05
150
I don't think sending your data over 3rd party proxy is a good idea
– Daniel Alexandrov
Oct 16 '15 at 14:07
9
One downside is they are sometimes overloaded, as they are now.This application is temporarily over its serving quota. Please try again later.
– evelynhathaway
Feb 20 '16 at 7:52
17
try toohttps://crossorigin.me/http://example.com
– KingRider
Apr 15 '16 at 15:05
|
show 12 more comments
I wish someone shared this site with me long ago http://cors.io/ it would have saved a ton of time compared to building and relying on my own proxy. However, as you move to production, having your own proxy is the best bet since you still control all aspects of your data.
All you need:
https://cors.io/?http://HTTP_YOUR_LINK_HERE
I wish someone shared this site with me long ago http://cors.io/ it would have saved a ton of time compared to building and relying on my own proxy. However, as you move to production, having your own proxy is the best bet since you still control all aspects of your data.
All you need:
https://cors.io/?http://HTTP_YOUR_LINK_HERE
edited Mar 9 '18 at 8:51
answered Jul 21 '15 at 22:08
yoshyoshyoshyosh
9,767133446
9,767133446
27
What are the downsides of this? Are those guys intercepting my data?
– Sebastialonso
Aug 21 '15 at 16:33
6
cors.io/?u=HTTP_YOUR_LINK_HERE (small correction)
– jkpd
Sep 17 '15 at 13:05
150
I don't think sending your data over 3rd party proxy is a good idea
– Daniel Alexandrov
Oct 16 '15 at 14:07
9
One downside is they are sometimes overloaded, as they are now.This application is temporarily over its serving quota. Please try again later.
– evelynhathaway
Feb 20 '16 at 7:52
17
try toohttps://crossorigin.me/http://example.com
– KingRider
Apr 15 '16 at 15:05
|
show 12 more comments
27
What are the downsides of this? Are those guys intercepting my data?
– Sebastialonso
Aug 21 '15 at 16:33
6
cors.io/?u=HTTP_YOUR_LINK_HERE (small correction)
– jkpd
Sep 17 '15 at 13:05
150
I don't think sending your data over 3rd party proxy is a good idea
– Daniel Alexandrov
Oct 16 '15 at 14:07
9
One downside is they are sometimes overloaded, as they are now.This application is temporarily over its serving quota. Please try again later.
– evelynhathaway
Feb 20 '16 at 7:52
17
try toohttps://crossorigin.me/http://example.com
– KingRider
Apr 15 '16 at 15:05
27
27
What are the downsides of this? Are those guys intercepting my data?
– Sebastialonso
Aug 21 '15 at 16:33
What are the downsides of this? Are those guys intercepting my data?
– Sebastialonso
Aug 21 '15 at 16:33
6
6
cors.io/?u=HTTP_YOUR_LINK_HERE (small correction)
– jkpd
Sep 17 '15 at 13:05
cors.io/?u=HTTP_YOUR_LINK_HERE (small correction)
– jkpd
Sep 17 '15 at 13:05
150
150
I don't think sending your data over 3rd party proxy is a good idea
– Daniel Alexandrov
Oct 16 '15 at 14:07
I don't think sending your data over 3rd party proxy is a good idea
– Daniel Alexandrov
Oct 16 '15 at 14:07
9
9
One downside is they are sometimes overloaded, as they are now.
This application is temporarily over its serving quota. Please try again later.
– evelynhathaway
Feb 20 '16 at 7:52
One downside is they are sometimes overloaded, as they are now.
This application is temporarily over its serving quota. Please try again later.
– evelynhathaway
Feb 20 '16 at 7:52
17
17
try too
https://crossorigin.me/http://example.com
– KingRider
Apr 15 '16 at 15:05
try too
https://crossorigin.me/http://example.com
– KingRider
Apr 15 '16 at 15:05
|
show 12 more comments
If you are using Node.js, try it:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
More information: CORS on ExpressJS
5
I am giving you the up vote because this is exactly what I needed. But think it is a bad idea to promote the "*" example without explaining that it will allow any connection and should not be used in production. This is explained at the MDN link developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
– rob
Jun 9 '17 at 9:12
@rob thanks for your comment. You are right, we should specify which origins are allowed to use the resources. But in case, the resources use for public purpose and we don't know the consumers, I think we should go with "*" if I am not wrong.
– Nguyen Tran
Jun 9 '17 at 11:08
I have used this concept and my issue is resolved in nodejs. Thanks
– Deepak Bhatta
Aug 20 '17 at 7:29
app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); res.setHeader('Access-Control-Allow-Credentials', true); if ('OPTIONS' === req.method) { res.send(204); } else { next(); } });
– Ricky sharma
Sep 26 '17 at 10:05
1
Regarding dangers of using"Access-Control-Allow-Origin", "*"
, see security.stackexchange.com/a/45677. tldr: W3 spec actually advises that: A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*"
– CODE-REaD
Feb 15 '18 at 16:45
add a comment |
If you are using Node.js, try it:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
More information: CORS on ExpressJS
5
I am giving you the up vote because this is exactly what I needed. But think it is a bad idea to promote the "*" example without explaining that it will allow any connection and should not be used in production. This is explained at the MDN link developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
– rob
Jun 9 '17 at 9:12
@rob thanks for your comment. You are right, we should specify which origins are allowed to use the resources. But in case, the resources use for public purpose and we don't know the consumers, I think we should go with "*" if I am not wrong.
– Nguyen Tran
Jun 9 '17 at 11:08
I have used this concept and my issue is resolved in nodejs. Thanks
– Deepak Bhatta
Aug 20 '17 at 7:29
app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); res.setHeader('Access-Control-Allow-Credentials', true); if ('OPTIONS' === req.method) { res.send(204); } else { next(); } });
– Ricky sharma
Sep 26 '17 at 10:05
1
Regarding dangers of using"Access-Control-Allow-Origin", "*"
, see security.stackexchange.com/a/45677. tldr: W3 spec actually advises that: A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*"
– CODE-REaD
Feb 15 '18 at 16:45
add a comment |
If you are using Node.js, try it:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
More information: CORS on ExpressJS
If you are using Node.js, try it:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
More information: CORS on ExpressJS
edited Feb 16 '16 at 23:53
Peter Mortensen
13.8k1987113
13.8k1987113
answered Feb 12 '16 at 16:27
Nguyen TranNguyen Tran
9551016
9551016
5
I am giving you the up vote because this is exactly what I needed. But think it is a bad idea to promote the "*" example without explaining that it will allow any connection and should not be used in production. This is explained at the MDN link developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
– rob
Jun 9 '17 at 9:12
@rob thanks for your comment. You are right, we should specify which origins are allowed to use the resources. But in case, the resources use for public purpose and we don't know the consumers, I think we should go with "*" if I am not wrong.
– Nguyen Tran
Jun 9 '17 at 11:08
I have used this concept and my issue is resolved in nodejs. Thanks
– Deepak Bhatta
Aug 20 '17 at 7:29
app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); res.setHeader('Access-Control-Allow-Credentials', true); if ('OPTIONS' === req.method) { res.send(204); } else { next(); } });
– Ricky sharma
Sep 26 '17 at 10:05
1
Regarding dangers of using"Access-Control-Allow-Origin", "*"
, see security.stackexchange.com/a/45677. tldr: W3 spec actually advises that: A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*"
– CODE-REaD
Feb 15 '18 at 16:45
add a comment |
5
I am giving you the up vote because this is exactly what I needed. But think it is a bad idea to promote the "*" example without explaining that it will allow any connection and should not be used in production. This is explained at the MDN link developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
– rob
Jun 9 '17 at 9:12
@rob thanks for your comment. You are right, we should specify which origins are allowed to use the resources. But in case, the resources use for public purpose and we don't know the consumers, I think we should go with "*" if I am not wrong.
– Nguyen Tran
Jun 9 '17 at 11:08
I have used this concept and my issue is resolved in nodejs. Thanks
– Deepak Bhatta
Aug 20 '17 at 7:29
app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); res.setHeader('Access-Control-Allow-Credentials', true); if ('OPTIONS' === req.method) { res.send(204); } else { next(); } });
– Ricky sharma
Sep 26 '17 at 10:05
1
Regarding dangers of using"Access-Control-Allow-Origin", "*"
, see security.stackexchange.com/a/45677. tldr: W3 spec actually advises that: A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*"
– CODE-REaD
Feb 15 '18 at 16:45
5
5
I am giving you the up vote because this is exactly what I needed. But think it is a bad idea to promote the "*" example without explaining that it will allow any connection and should not be used in production. This is explained at the MDN link developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
– rob
Jun 9 '17 at 9:12
I am giving you the up vote because this is exactly what I needed. But think it is a bad idea to promote the "*" example without explaining that it will allow any connection and should not be used in production. This is explained at the MDN link developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
– rob
Jun 9 '17 at 9:12
@rob thanks for your comment. You are right, we should specify which origins are allowed to use the resources. But in case, the resources use for public purpose and we don't know the consumers, I think we should go with "*" if I am not wrong.
– Nguyen Tran
Jun 9 '17 at 11:08
@rob thanks for your comment. You are right, we should specify which origins are allowed to use the resources. But in case, the resources use for public purpose and we don't know the consumers, I think we should go with "*" if I am not wrong.
– Nguyen Tran
Jun 9 '17 at 11:08
I have used this concept and my issue is resolved in nodejs. Thanks
– Deepak Bhatta
Aug 20 '17 at 7:29
I have used this concept and my issue is resolved in nodejs. Thanks
– Deepak Bhatta
Aug 20 '17 at 7:29
app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); res.setHeader('Access-Control-Allow-Credentials', true); if ('OPTIONS' === req.method) { res.send(204); } else { next(); } });
– Ricky sharma
Sep 26 '17 at 10:05
app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); res.setHeader('Access-Control-Allow-Credentials', true); if ('OPTIONS' === req.method) { res.send(204); } else { next(); } });
– Ricky sharma
Sep 26 '17 at 10:05
1
1
Regarding dangers of using
"Access-Control-Allow-Origin", "*"
, see security.stackexchange.com/a/45677. tldr: W3 spec actually advises that: A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*"– CODE-REaD
Feb 15 '18 at 16:45
Regarding dangers of using
"Access-Control-Allow-Origin", "*"
, see security.stackexchange.com/a/45677. tldr: W3 spec actually advises that: A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*"– CODE-REaD
Feb 15 '18 at 16:45
add a comment |
There's a cross-domain issue using Ajax. You must be sure you are accessing your files on the same http://
path without www.
(or access from http://www.
and post to the same path including www.
) which the browser considers as another domain when accessing via a www.
path, so you see where the problem is. You are posting to a different domain and the browser blocks the flow because of the origin issue.
If the API is not placed on the same host that you are requesting from, the flow is blocked, and you will need to find another way to communicate with the API.
yup, i was forced to this in my phonegap app, var app_url = location.protocol + '//' + location.host+'/api/. the problem was the site with www. prepended would bring that error.
– Sir Lojik
Apr 27 '15 at 12:26
add a comment |
There's a cross-domain issue using Ajax. You must be sure you are accessing your files on the same http://
path without www.
(or access from http://www.
and post to the same path including www.
) which the browser considers as another domain when accessing via a www.
path, so you see where the problem is. You are posting to a different domain and the browser blocks the flow because of the origin issue.
If the API is not placed on the same host that you are requesting from, the flow is blocked, and you will need to find another way to communicate with the API.
yup, i was forced to this in my phonegap app, var app_url = location.protocol + '//' + location.host+'/api/. the problem was the site with www. prepended would bring that error.
– Sir Lojik
Apr 27 '15 at 12:26
add a comment |
There's a cross-domain issue using Ajax. You must be sure you are accessing your files on the same http://
path without www.
(or access from http://www.
and post to the same path including www.
) which the browser considers as another domain when accessing via a www.
path, so you see where the problem is. You are posting to a different domain and the browser blocks the flow because of the origin issue.
If the API is not placed on the same host that you are requesting from, the flow is blocked, and you will need to find another way to communicate with the API.
There's a cross-domain issue using Ajax. You must be sure you are accessing your files on the same http://
path without www.
(or access from http://www.
and post to the same path including www.
) which the browser considers as another domain when accessing via a www.
path, so you see where the problem is. You are posting to a different domain and the browser blocks the flow because of the origin issue.
If the API is not placed on the same host that you are requesting from, the flow is blocked, and you will need to find another way to communicate with the API.
edited Apr 2 '15 at 9:31
answered Mar 12 '14 at 8:53
Alin RazvanAlin Razvan
996910
996910
yup, i was forced to this in my phonegap app, var app_url = location.protocol + '//' + location.host+'/api/. the problem was the site with www. prepended would bring that error.
– Sir Lojik
Apr 27 '15 at 12:26
add a comment |
yup, i was forced to this in my phonegap app, var app_url = location.protocol + '//' + location.host+'/api/. the problem was the site with www. prepended would bring that error.
– Sir Lojik
Apr 27 '15 at 12:26
yup, i was forced to this in my phonegap app, var app_url = location.protocol + '//' + location.host+'/api/. the problem was the site with www. prepended would bring that error.
– Sir Lojik
Apr 27 '15 at 12:26
yup, i was forced to this in my phonegap app, var app_url = location.protocol + '//' + location.host+'/api/. the problem was the site with www. prepended would bring that error.
– Sir Lojik
Apr 27 '15 at 12:26
add a comment |
Because
$.ajax({type: "POST" - Calls OPTIONS
$.post( - Calls POST
both are different Postman calls "POST" properly but when we call it will be "OPTIONS"
For c# web services - webapi
Please add the following code in your web.config file under <system.webServer> tag. This will work
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Please make sure you are not doing any mistake in the ajax call
jQuery
$.ajax({
url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST", /* or type:"GET" or type:"PUT" */
dataType: "json",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
Angular 4 issue please refer : http://www.hubfly.com/blog/solutions/how-to-fix-angular-4-api-call-issues/
Note: If you are looking for downloading content from third party website then this will not help you. You can try the following code but not JavaScript.
System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");
This config solved same error on Wordpress at Azure Services. Thanks.
– Andre Mesquita
May 22 '17 at 13:41
8
I would suggest using a specific origin value to avoid requests from external domains. So for example instead of*
usehttps://www.myotherdomain.com
– pechar
Jun 9 '17 at 8:30
add a comment |
Because
$.ajax({type: "POST" - Calls OPTIONS
$.post( - Calls POST
both are different Postman calls "POST" properly but when we call it will be "OPTIONS"
For c# web services - webapi
Please add the following code in your web.config file under <system.webServer> tag. This will work
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Please make sure you are not doing any mistake in the ajax call
jQuery
$.ajax({
url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST", /* or type:"GET" or type:"PUT" */
dataType: "json",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
Angular 4 issue please refer : http://www.hubfly.com/blog/solutions/how-to-fix-angular-4-api-call-issues/
Note: If you are looking for downloading content from third party website then this will not help you. You can try the following code but not JavaScript.
System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");
This config solved same error on Wordpress at Azure Services. Thanks.
– Andre Mesquita
May 22 '17 at 13:41
8
I would suggest using a specific origin value to avoid requests from external domains. So for example instead of*
usehttps://www.myotherdomain.com
– pechar
Jun 9 '17 at 8:30
add a comment |
Because
$.ajax({type: "POST" - Calls OPTIONS
$.post( - Calls POST
both are different Postman calls "POST" properly but when we call it will be "OPTIONS"
For c# web services - webapi
Please add the following code in your web.config file under <system.webServer> tag. This will work
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Please make sure you are not doing any mistake in the ajax call
jQuery
$.ajax({
url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST", /* or type:"GET" or type:"PUT" */
dataType: "json",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
Angular 4 issue please refer : http://www.hubfly.com/blog/solutions/how-to-fix-angular-4-api-call-issues/
Note: If you are looking for downloading content from third party website then this will not help you. You can try the following code but not JavaScript.
System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");
Because
$.ajax({type: "POST" - Calls OPTIONS
$.post( - Calls POST
both are different Postman calls "POST" properly but when we call it will be "OPTIONS"
For c# web services - webapi
Please add the following code in your web.config file under <system.webServer> tag. This will work
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Please make sure you are not doing any mistake in the ajax call
jQuery
$.ajax({
url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST", /* or type:"GET" or type:"PUT" */
dataType: "json",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
Angular 4 issue please refer : http://www.hubfly.com/blog/solutions/how-to-fix-angular-4-api-call-issues/
Note: If you are looking for downloading content from third party website then this will not help you. You can try the following code but not JavaScript.
System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");
edited Nov 13 '18 at 9:27
answered Dec 13 '16 at 13:02
George LivingstonGeorge Livingston
1,10689
1,10689
This config solved same error on Wordpress at Azure Services. Thanks.
– Andre Mesquita
May 22 '17 at 13:41
8
I would suggest using a specific origin value to avoid requests from external domains. So for example instead of*
usehttps://www.myotherdomain.com
– pechar
Jun 9 '17 at 8:30
add a comment |
This config solved same error on Wordpress at Azure Services. Thanks.
– Andre Mesquita
May 22 '17 at 13:41
8
I would suggest using a specific origin value to avoid requests from external domains. So for example instead of*
usehttps://www.myotherdomain.com
– pechar
Jun 9 '17 at 8:30
This config solved same error on Wordpress at Azure Services. Thanks.
– Andre Mesquita
May 22 '17 at 13:41
This config solved same error on Wordpress at Azure Services. Thanks.
– Andre Mesquita
May 22 '17 at 13:41
8
8
I would suggest using a specific origin value to avoid requests from external domains. So for example instead of
*
use https://www.myotherdomain.com
– pechar
Jun 9 '17 at 8:30
I would suggest using a specific origin value to avoid requests from external domains. So for example instead of
*
use https://www.myotherdomain.com
– pechar
Jun 9 '17 at 8:30
add a comment |
Try XDomain,
Summary: A pure JavaScript CORS alternative/polyfill. No server configuration required - just add a proxy.html on the domain you wish to communicate with. This library uses XHook to hook all XHR, so XDomain should work in conjunction with any library.
add a comment |
Try XDomain,
Summary: A pure JavaScript CORS alternative/polyfill. No server configuration required - just add a proxy.html on the domain you wish to communicate with. This library uses XHook to hook all XHR, so XDomain should work in conjunction with any library.
add a comment |
Try XDomain,
Summary: A pure JavaScript CORS alternative/polyfill. No server configuration required - just add a proxy.html on the domain you wish to communicate with. This library uses XHook to hook all XHR, so XDomain should work in conjunction with any library.
Try XDomain,
Summary: A pure JavaScript CORS alternative/polyfill. No server configuration required - just add a proxy.html on the domain you wish to communicate with. This library uses XHook to hook all XHR, so XDomain should work in conjunction with any library.
edited Jan 9 '15 at 19:19
ygormutti
143113
143113
answered Apr 1 '14 at 7:46
user3359786user3359786
22122
22122
add a comment |
add a comment |
If you do NOT want to:
- Disable web security in Chrome
- Use JSONP
- Use a third party site to re-route your requests
and you are sure that your server has CORS enabled then (test CORS here: http://www.test-cors.org/)
Then you need to pass in origin parameter with your request.
This origin MUST match the origin that your browser sends with your request.
You can see it in action here:
http://www.wikinomad.com/app/detail/Campgrounds/3591
The edit functionality sends a GET & POST request to a different domain for fetching data. I set the origin parameter which resolves the issue.
The backend is a mediaWiki engine.
tldr: Add "origin" parameter to your calls which must be the Origin parameter that your browser sends (you cannot spoof the origin parameter)
1
Are your referring to this example code from main.min.js?:t.post("https://wiki.wikinomad.com/api.php?origin=https://www.wikinomad.com", n, o).then(function(e) {...
. If so, isn't it true that this way of specifying an origin requires that the PHP being served from the "backend" is coded to support it, and this answer will not work otherwise?
– CODE-REaD
Feb 15 '18 at 20:18
1
@CODE-REaD, yes that's correct that the backend needs to support CORS as well.
– Ganesh Krishnan
Jan 19 at 17:55
add a comment |
If you do NOT want to:
- Disable web security in Chrome
- Use JSONP
- Use a third party site to re-route your requests
and you are sure that your server has CORS enabled then (test CORS here: http://www.test-cors.org/)
Then you need to pass in origin parameter with your request.
This origin MUST match the origin that your browser sends with your request.
You can see it in action here:
http://www.wikinomad.com/app/detail/Campgrounds/3591
The edit functionality sends a GET & POST request to a different domain for fetching data. I set the origin parameter which resolves the issue.
The backend is a mediaWiki engine.
tldr: Add "origin" parameter to your calls which must be the Origin parameter that your browser sends (you cannot spoof the origin parameter)
1
Are your referring to this example code from main.min.js?:t.post("https://wiki.wikinomad.com/api.php?origin=https://www.wikinomad.com", n, o).then(function(e) {...
. If so, isn't it true that this way of specifying an origin requires that the PHP being served from the "backend" is coded to support it, and this answer will not work otherwise?
– CODE-REaD
Feb 15 '18 at 20:18
1
@CODE-REaD, yes that's correct that the backend needs to support CORS as well.
– Ganesh Krishnan
Jan 19 at 17:55
add a comment |
If you do NOT want to:
- Disable web security in Chrome
- Use JSONP
- Use a third party site to re-route your requests
and you are sure that your server has CORS enabled then (test CORS here: http://www.test-cors.org/)
Then you need to pass in origin parameter with your request.
This origin MUST match the origin that your browser sends with your request.
You can see it in action here:
http://www.wikinomad.com/app/detail/Campgrounds/3591
The edit functionality sends a GET & POST request to a different domain for fetching data. I set the origin parameter which resolves the issue.
The backend is a mediaWiki engine.
tldr: Add "origin" parameter to your calls which must be the Origin parameter that your browser sends (you cannot spoof the origin parameter)
If you do NOT want to:
- Disable web security in Chrome
- Use JSONP
- Use a third party site to re-route your requests
and you are sure that your server has CORS enabled then (test CORS here: http://www.test-cors.org/)
Then you need to pass in origin parameter with your request.
This origin MUST match the origin that your browser sends with your request.
You can see it in action here:
http://www.wikinomad.com/app/detail/Campgrounds/3591
The edit functionality sends a GET & POST request to a different domain for fetching data. I set the origin parameter which resolves the issue.
The backend is a mediaWiki engine.
tldr: Add "origin" parameter to your calls which must be the Origin parameter that your browser sends (you cannot spoof the origin parameter)
edited Jan 19 at 17:54
answered Jul 7 '16 at 4:26
Ganesh KrishnanGanesh Krishnan
4,49423040
4,49423040
1
Are your referring to this example code from main.min.js?:t.post("https://wiki.wikinomad.com/api.php?origin=https://www.wikinomad.com", n, o).then(function(e) {...
. If so, isn't it true that this way of specifying an origin requires that the PHP being served from the "backend" is coded to support it, and this answer will not work otherwise?
– CODE-REaD
Feb 15 '18 at 20:18
1
@CODE-REaD, yes that's correct that the backend needs to support CORS as well.
– Ganesh Krishnan
Jan 19 at 17:55
add a comment |
1
Are your referring to this example code from main.min.js?:t.post("https://wiki.wikinomad.com/api.php?origin=https://www.wikinomad.com", n, o).then(function(e) {...
. If so, isn't it true that this way of specifying an origin requires that the PHP being served from the "backend" is coded to support it, and this answer will not work otherwise?
– CODE-REaD
Feb 15 '18 at 20:18
1
@CODE-REaD, yes that's correct that the backend needs to support CORS as well.
– Ganesh Krishnan
Jan 19 at 17:55
1
1
Are your referring to this example code from main.min.js?:
t.post("https://wiki.wikinomad.com/api.php?origin=https://www.wikinomad.com", n, o).then(function(e) {...
. If so, isn't it true that this way of specifying an origin requires that the PHP being served from the "backend" is coded to support it, and this answer will not work otherwise?– CODE-REaD
Feb 15 '18 at 20:18
Are your referring to this example code from main.min.js?:
t.post("https://wiki.wikinomad.com/api.php?origin=https://www.wikinomad.com", n, o).then(function(e) {...
. If so, isn't it true that this way of specifying an origin requires that the PHP being served from the "backend" is coded to support it, and this answer will not work otherwise?– CODE-REaD
Feb 15 '18 at 20:18
1
1
@CODE-REaD, yes that's correct that the backend needs to support CORS as well.
– Ganesh Krishnan
Jan 19 at 17:55
@CODE-REaD, yes that's correct that the backend needs to support CORS as well.
– Ganesh Krishnan
Jan 19 at 17:55
add a comment |
I had a problem with this when I used AngularJS to access my API. The same request worked in SoapUI 5.0 and ColdFusion. My GET method already had Access-Control-Allow-Origin header.
I found out that AngularJS makes a "trial" OPTIONS request. ColdFusion, by default, generates OPTIONS method, but it doesn’t have much, these headers specifically. The error was generated in response to that OPTIONS call, and not to my intentional call to GET. After I added OPTIONS method below to my API, the problem has been resolved.
<cffunction name="optionsMethod" access="remote" output="false" returntype="any" httpmethod="OPTIONS" description="Method to respond to AngularJS trial call">
<cfheader name="Access-Control-Allow-Headers" value="Content-Type,x-requested-with,Authorization,Access-Control-Allow-Origin">
<cfheader name="Access-Control-Allow-Methods" value="GET,OPTIONS">
<cfheader name="Access-Control-Allow-Origin" value="*">
<cfheader name="Access-Control-Max-Age" value="360">
</cffunction>
5
It's not angular that makes the OPTIONS request, it's the browser based on the request!
– Narretz
Oct 12 '15 at 17:36
1
Narretz - calling API via browser doesn't produce this error, nor it makes an extra options call. When angular used it does.
– Leonid Alzhin
Nov 17 '15 at 0:20
3
Narretz is right, it is not related to angular. It's related to how CORS works.
– Emile Bergeron
Oct 18 '16 at 15:23
add a comment |
I had a problem with this when I used AngularJS to access my API. The same request worked in SoapUI 5.0 and ColdFusion. My GET method already had Access-Control-Allow-Origin header.
I found out that AngularJS makes a "trial" OPTIONS request. ColdFusion, by default, generates OPTIONS method, but it doesn’t have much, these headers specifically. The error was generated in response to that OPTIONS call, and not to my intentional call to GET. After I added OPTIONS method below to my API, the problem has been resolved.
<cffunction name="optionsMethod" access="remote" output="false" returntype="any" httpmethod="OPTIONS" description="Method to respond to AngularJS trial call">
<cfheader name="Access-Control-Allow-Headers" value="Content-Type,x-requested-with,Authorization,Access-Control-Allow-Origin">
<cfheader name="Access-Control-Allow-Methods" value="GET,OPTIONS">
<cfheader name="Access-Control-Allow-Origin" value="*">
<cfheader name="Access-Control-Max-Age" value="360">
</cffunction>
5
It's not angular that makes the OPTIONS request, it's the browser based on the request!
– Narretz
Oct 12 '15 at 17:36
1
Narretz - calling API via browser doesn't produce this error, nor it makes an extra options call. When angular used it does.
– Leonid Alzhin
Nov 17 '15 at 0:20
3
Narretz is right, it is not related to angular. It's related to how CORS works.
– Emile Bergeron
Oct 18 '16 at 15:23
add a comment |
I had a problem with this when I used AngularJS to access my API. The same request worked in SoapUI 5.0 and ColdFusion. My GET method already had Access-Control-Allow-Origin header.
I found out that AngularJS makes a "trial" OPTIONS request. ColdFusion, by default, generates OPTIONS method, but it doesn’t have much, these headers specifically. The error was generated in response to that OPTIONS call, and not to my intentional call to GET. After I added OPTIONS method below to my API, the problem has been resolved.
<cffunction name="optionsMethod" access="remote" output="false" returntype="any" httpmethod="OPTIONS" description="Method to respond to AngularJS trial call">
<cfheader name="Access-Control-Allow-Headers" value="Content-Type,x-requested-with,Authorization,Access-Control-Allow-Origin">
<cfheader name="Access-Control-Allow-Methods" value="GET,OPTIONS">
<cfheader name="Access-Control-Allow-Origin" value="*">
<cfheader name="Access-Control-Max-Age" value="360">
</cffunction>
I had a problem with this when I used AngularJS to access my API. The same request worked in SoapUI 5.0 and ColdFusion. My GET method already had Access-Control-Allow-Origin header.
I found out that AngularJS makes a "trial" OPTIONS request. ColdFusion, by default, generates OPTIONS method, but it doesn’t have much, these headers specifically. The error was generated in response to that OPTIONS call, and not to my intentional call to GET. After I added OPTIONS method below to my API, the problem has been resolved.
<cffunction name="optionsMethod" access="remote" output="false" returntype="any" httpmethod="OPTIONS" description="Method to respond to AngularJS trial call">
<cfheader name="Access-Control-Allow-Headers" value="Content-Type,x-requested-with,Authorization,Access-Control-Allow-Origin">
<cfheader name="Access-Control-Allow-Methods" value="GET,OPTIONS">
<cfheader name="Access-Control-Allow-Origin" value="*">
<cfheader name="Access-Control-Max-Age" value="360">
</cffunction>
answered Jan 29 '15 at 0:06
Leonid AlzhinLeonid Alzhin
12617
12617
5
It's not angular that makes the OPTIONS request, it's the browser based on the request!
– Narretz
Oct 12 '15 at 17:36
1
Narretz - calling API via browser doesn't produce this error, nor it makes an extra options call. When angular used it does.
– Leonid Alzhin
Nov 17 '15 at 0:20
3
Narretz is right, it is not related to angular. It's related to how CORS works.
– Emile Bergeron
Oct 18 '16 at 15:23
add a comment |
5
It's not angular that makes the OPTIONS request, it's the browser based on the request!
– Narretz
Oct 12 '15 at 17:36
1
Narretz - calling API via browser doesn't produce this error, nor it makes an extra options call. When angular used it does.
– Leonid Alzhin
Nov 17 '15 at 0:20
3
Narretz is right, it is not related to angular. It's related to how CORS works.
– Emile Bergeron
Oct 18 '16 at 15:23
5
5
It's not angular that makes the OPTIONS request, it's the browser based on the request!
– Narretz
Oct 12 '15 at 17:36
It's not angular that makes the OPTIONS request, it's the browser based on the request!
– Narretz
Oct 12 '15 at 17:36
1
1
Narretz - calling API via browser doesn't produce this error, nor it makes an extra options call. When angular used it does.
– Leonid Alzhin
Nov 17 '15 at 0:20
Narretz - calling API via browser doesn't produce this error, nor it makes an extra options call. When angular used it does.
– Leonid Alzhin
Nov 17 '15 at 0:20
3
3
Narretz is right, it is not related to angular. It's related to how CORS works.
– Emile Bergeron
Oct 18 '16 at 15:23
Narretz is right, it is not related to angular. It's related to how CORS works.
– Emile Bergeron
Oct 18 '16 at 15:23
add a comment |
I had the following configuration, resulting in the same error, when requesting responses from the server.
Server-side: SparkJava --> provides the REST-API
Client-side: ExtJs6 --> provides Browser rendering
On the server-side I had to add this to the response:
Spark.get("/someRestCallToSpark", (req, res) -> {
res.header("Access-Control-Allow-Origin", "*"); //important, otherwise its not working
return "some text";
});
On the client-side I had to add this to the request:
Ext.Ajax.request({
url: "http://localhost:4567/someRestCallToSpark",
useDefaultXhrHeader: false, //important, otherwise its not working
success: function(response, opts) {console.log("success")},
failure: function(response, opts) {console.log("failure")}
});
Had the same architecture, therefore the same problem, and this solve it.
– Fafhrd
Oct 7 '15 at 19:03
3
This is not a good idea to allow requests from any domain. You should restrict it to trusted domain only.
– MD. Sahib Bin Mahboob
Jan 15 '16 at 5:36
If you are the host of both domains, then it is common practice to enable this type of requests.
– kiltek
May 25 '16 at 8:42
add a comment |
I had the following configuration, resulting in the same error, when requesting responses from the server.
Server-side: SparkJava --> provides the REST-API
Client-side: ExtJs6 --> provides Browser rendering
On the server-side I had to add this to the response:
Spark.get("/someRestCallToSpark", (req, res) -> {
res.header("Access-Control-Allow-Origin", "*"); //important, otherwise its not working
return "some text";
});
On the client-side I had to add this to the request:
Ext.Ajax.request({
url: "http://localhost:4567/someRestCallToSpark",
useDefaultXhrHeader: false, //important, otherwise its not working
success: function(response, opts) {console.log("success")},
failure: function(response, opts) {console.log("failure")}
});
Had the same architecture, therefore the same problem, and this solve it.
– Fafhrd
Oct 7 '15 at 19:03
3
This is not a good idea to allow requests from any domain. You should restrict it to trusted domain only.
– MD. Sahib Bin Mahboob
Jan 15 '16 at 5:36
If you are the host of both domains, then it is common practice to enable this type of requests.
– kiltek
May 25 '16 at 8:42
add a comment |
I had the following configuration, resulting in the same error, when requesting responses from the server.
Server-side: SparkJava --> provides the REST-API
Client-side: ExtJs6 --> provides Browser rendering
On the server-side I had to add this to the response:
Spark.get("/someRestCallToSpark", (req, res) -> {
res.header("Access-Control-Allow-Origin", "*"); //important, otherwise its not working
return "some text";
});
On the client-side I had to add this to the request:
Ext.Ajax.request({
url: "http://localhost:4567/someRestCallToSpark",
useDefaultXhrHeader: false, //important, otherwise its not working
success: function(response, opts) {console.log("success")},
failure: function(response, opts) {console.log("failure")}
});
I had the following configuration, resulting in the same error, when requesting responses from the server.
Server-side: SparkJava --> provides the REST-API
Client-side: ExtJs6 --> provides Browser rendering
On the server-side I had to add this to the response:
Spark.get("/someRestCallToSpark", (req, res) -> {
res.header("Access-Control-Allow-Origin", "*"); //important, otherwise its not working
return "some text";
});
On the client-side I had to add this to the request:
Ext.Ajax.request({
url: "http://localhost:4567/someRestCallToSpark",
useDefaultXhrHeader: false, //important, otherwise its not working
success: function(response, opts) {console.log("success")},
failure: function(response, opts) {console.log("failure")}
});
edited Jun 28 '16 at 3:46
Ani Menon
16.2k85978
16.2k85978
answered Sep 18 '15 at 14:50
kiltekkiltek
1,71843560
1,71843560
Had the same architecture, therefore the same problem, and this solve it.
– Fafhrd
Oct 7 '15 at 19:03
3
This is not a good idea to allow requests from any domain. You should restrict it to trusted domain only.
– MD. Sahib Bin Mahboob
Jan 15 '16 at 5:36
If you are the host of both domains, then it is common practice to enable this type of requests.
– kiltek
May 25 '16 at 8:42
add a comment |
Had the same architecture, therefore the same problem, and this solve it.
– Fafhrd
Oct 7 '15 at 19:03
3
This is not a good idea to allow requests from any domain. You should restrict it to trusted domain only.
– MD. Sahib Bin Mahboob
Jan 15 '16 at 5:36
If you are the host of both domains, then it is common practice to enable this type of requests.
– kiltek
May 25 '16 at 8:42
Had the same architecture, therefore the same problem, and this solve it.
– Fafhrd
Oct 7 '15 at 19:03
Had the same architecture, therefore the same problem, and this solve it.
– Fafhrd
Oct 7 '15 at 19:03
3
3
This is not a good idea to allow requests from any domain. You should restrict it to trusted domain only.
– MD. Sahib Bin Mahboob
Jan 15 '16 at 5:36
This is not a good idea to allow requests from any domain. You should restrict it to trusted domain only.
– MD. Sahib Bin Mahboob
Jan 15 '16 at 5:36
If you are the host of both domains, then it is common practice to enable this type of requests.
– kiltek
May 25 '16 at 8:42
If you are the host of both domains, then it is common practice to enable this type of requests.
– kiltek
May 25 '16 at 8:42
add a comment |
Based on shruti's answer, I've created a shortcut of Chrome browser with needed arguments:
69
Excellent. Now I have to go around to my 100,000 users and disable their web security on chrome.
– Ganesh Krishnan
Jul 6 '16 at 6:08
7
@GaneshKrishnan The questioner seems to be a developer and his question (in my opinion) seems for development purposes, as my problem was. And yes, if you want to hack your users, go around them and disable their web security on Chrome :)
– Mohammad AlBanna
Jul 6 '16 at 18:37
add a comment |
Based on shruti's answer, I've created a shortcut of Chrome browser with needed arguments:
69
Excellent. Now I have to go around to my 100,000 users and disable their web security on chrome.
– Ganesh Krishnan
Jul 6 '16 at 6:08
7
@GaneshKrishnan The questioner seems to be a developer and his question (in my opinion) seems for development purposes, as my problem was. And yes, if you want to hack your users, go around them and disable their web security on Chrome :)
– Mohammad AlBanna
Jul 6 '16 at 18:37
add a comment |
Based on shruti's answer, I've created a shortcut of Chrome browser with needed arguments:
Based on shruti's answer, I've created a shortcut of Chrome browser with needed arguments:
edited May 23 '17 at 11:47
Community♦
11
11
answered Jul 2 '16 at 23:52
Mohammad AlBannaMohammad AlBanna
1,3031117
1,3031117
69
Excellent. Now I have to go around to my 100,000 users and disable their web security on chrome.
– Ganesh Krishnan
Jul 6 '16 at 6:08
7
@GaneshKrishnan The questioner seems to be a developer and his question (in my opinion) seems for development purposes, as my problem was. And yes, if you want to hack your users, go around them and disable their web security on Chrome :)
– Mohammad AlBanna
Jul 6 '16 at 18:37
add a comment |
69
Excellent. Now I have to go around to my 100,000 users and disable their web security on chrome.
– Ganesh Krishnan
Jul 6 '16 at 6:08
7
@GaneshKrishnan The questioner seems to be a developer and his question (in my opinion) seems for development purposes, as my problem was. And yes, if you want to hack your users, go around them and disable their web security on Chrome :)
– Mohammad AlBanna
Jul 6 '16 at 18:37
69
69
Excellent. Now I have to go around to my 100,000 users and disable their web security on chrome.
– Ganesh Krishnan
Jul 6 '16 at 6:08
Excellent. Now I have to go around to my 100,000 users and disable their web security on chrome.
– Ganesh Krishnan
Jul 6 '16 at 6:08
7
7
@GaneshKrishnan The questioner seems to be a developer and his question (in my opinion) seems for development purposes, as my problem was. And yes, if you want to hack your users, go around them and disable their web security on Chrome :)
– Mohammad AlBanna
Jul 6 '16 at 18:37
@GaneshKrishnan The questioner seems to be a developer and his question (in my opinion) seems for development purposes, as my problem was. And yes, if you want to hack your users, go around them and disable their web security on Chrome :)
– Mohammad AlBanna
Jul 6 '16 at 18:37
add a comment |
https://github.com/Rob--W/cors-anywhere/ provides (Node.js) code you can use to set up and run your own CORS proxy. It’s actively maintained and provides a number of features for controlling the proxy behavior beyond just the basic sending of the correct Access-Control-*
response headers.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has details to explain how browsers handle cross-origin requests that client-side web applications make from JavaScript and what headers you must configure sending of by the server the request is made to, if you can.
In the case where a site you need to make a request to and get a response from doesn’t return the Access-Control-Allow-Origin
response header, browsers are always going to block cross-origin requests made to it directly by your client-side JavaScript code from working. And so if the site is not one you control and can configure behavior for, the only thing that will work in that case is proxying the requests—either through your own proxy you run yourself or through an open proxy.
As mentioned in other comments here, there are good reasons for not trusting an open proxy with your requests. That said, if you know what you’re doing and you decide an open proxy works for your needs, https://cors-anywhere.herokuapp.com/ is one that’s reliably available, actively maintained, and that runs an instance of the https://github.com/Rob--W/cors-anywhere/ code.
As with other open proxies mentioned here (a couple of which at least don’t seem to be available any longer), the way it works is that instead of having your client code send a request directly to, e.g., http://foo.com
you send it to https://cors-anywhere.herokuapp.com/http://foo.com
and the proxy adds the necessary Access-Control-*
headers to the response the browser sees.
add a comment |
https://github.com/Rob--W/cors-anywhere/ provides (Node.js) code you can use to set up and run your own CORS proxy. It’s actively maintained and provides a number of features for controlling the proxy behavior beyond just the basic sending of the correct Access-Control-*
response headers.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has details to explain how browsers handle cross-origin requests that client-side web applications make from JavaScript and what headers you must configure sending of by the server the request is made to, if you can.
In the case where a site you need to make a request to and get a response from doesn’t return the Access-Control-Allow-Origin
response header, browsers are always going to block cross-origin requests made to it directly by your client-side JavaScript code from working. And so if the site is not one you control and can configure behavior for, the only thing that will work in that case is proxying the requests—either through your own proxy you run yourself or through an open proxy.
As mentioned in other comments here, there are good reasons for not trusting an open proxy with your requests. That said, if you know what you’re doing and you decide an open proxy works for your needs, https://cors-anywhere.herokuapp.com/ is one that’s reliably available, actively maintained, and that runs an instance of the https://github.com/Rob--W/cors-anywhere/ code.
As with other open proxies mentioned here (a couple of which at least don’t seem to be available any longer), the way it works is that instead of having your client code send a request directly to, e.g., http://foo.com
you send it to https://cors-anywhere.herokuapp.com/http://foo.com
and the proxy adds the necessary Access-Control-*
headers to the response the browser sees.
add a comment |
https://github.com/Rob--W/cors-anywhere/ provides (Node.js) code you can use to set up and run your own CORS proxy. It’s actively maintained and provides a number of features for controlling the proxy behavior beyond just the basic sending of the correct Access-Control-*
response headers.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has details to explain how browsers handle cross-origin requests that client-side web applications make from JavaScript and what headers you must configure sending of by the server the request is made to, if you can.
In the case where a site you need to make a request to and get a response from doesn’t return the Access-Control-Allow-Origin
response header, browsers are always going to block cross-origin requests made to it directly by your client-side JavaScript code from working. And so if the site is not one you control and can configure behavior for, the only thing that will work in that case is proxying the requests—either through your own proxy you run yourself or through an open proxy.
As mentioned in other comments here, there are good reasons for not trusting an open proxy with your requests. That said, if you know what you’re doing and you decide an open proxy works for your needs, https://cors-anywhere.herokuapp.com/ is one that’s reliably available, actively maintained, and that runs an instance of the https://github.com/Rob--W/cors-anywhere/ code.
As with other open proxies mentioned here (a couple of which at least don’t seem to be available any longer), the way it works is that instead of having your client code send a request directly to, e.g., http://foo.com
you send it to https://cors-anywhere.herokuapp.com/http://foo.com
and the proxy adds the necessary Access-Control-*
headers to the response the browser sees.
https://github.com/Rob--W/cors-anywhere/ provides (Node.js) code you can use to set up and run your own CORS proxy. It’s actively maintained and provides a number of features for controlling the proxy behavior beyond just the basic sending of the correct Access-Control-*
response headers.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has details to explain how browsers handle cross-origin requests that client-side web applications make from JavaScript and what headers you must configure sending of by the server the request is made to, if you can.
In the case where a site you need to make a request to and get a response from doesn’t return the Access-Control-Allow-Origin
response header, browsers are always going to block cross-origin requests made to it directly by your client-side JavaScript code from working. And so if the site is not one you control and can configure behavior for, the only thing that will work in that case is proxying the requests—either through your own proxy you run yourself or through an open proxy.
As mentioned in other comments here, there are good reasons for not trusting an open proxy with your requests. That said, if you know what you’re doing and you decide an open proxy works for your needs, https://cors-anywhere.herokuapp.com/ is one that’s reliably available, actively maintained, and that runs an instance of the https://github.com/Rob--W/cors-anywhere/ code.
As with other open proxies mentioned here (a couple of which at least don’t seem to be available any longer), the way it works is that instead of having your client code send a request directly to, e.g., http://foo.com
you send it to https://cors-anywhere.herokuapp.com/http://foo.com
and the proxy adds the necessary Access-Control-*
headers to the response the browser sees.
edited May 21 '17 at 10:39
Peter Mortensen
13.8k1987113
13.8k1987113
answered Mar 12 '17 at 7:01
sideshowbarkersideshowbarker
33.3k147997
33.3k147997
add a comment |
add a comment |
You can bypass the problem by using YQL to proxy the request through Yahoo's servers. It is just a few lines of code:
var yql_url = 'https://query.yahooapis.com/v1/public/yql';
var url = 'your api url';
$.ajax({
'url': yql_url,
'data': {
'q': 'SELECT * FROM json WHERE url="'+url+'"',
'format': 'json',
'jsonCompat': 'new',
},
'dataType': 'jsonp',
'success': function(response) {
console.log(response);
},
});
Here's the link with an explanation: https://vverma.net/fetch-any-json-using-jsonp-and-yql.html
but after seconds ... all the other codes run then it initialize.
– saber tabatabaee yazdi
Jun 8 '17 at 16:16
add a comment |
You can bypass the problem by using YQL to proxy the request through Yahoo's servers. It is just a few lines of code:
var yql_url = 'https://query.yahooapis.com/v1/public/yql';
var url = 'your api url';
$.ajax({
'url': yql_url,
'data': {
'q': 'SELECT * FROM json WHERE url="'+url+'"',
'format': 'json',
'jsonCompat': 'new',
},
'dataType': 'jsonp',
'success': function(response) {
console.log(response);
},
});
Here's the link with an explanation: https://vverma.net/fetch-any-json-using-jsonp-and-yql.html
but after seconds ... all the other codes run then it initialize.
– saber tabatabaee yazdi
Jun 8 '17 at 16:16
add a comment |
You can bypass the problem by using YQL to proxy the request through Yahoo's servers. It is just a few lines of code:
var yql_url = 'https://query.yahooapis.com/v1/public/yql';
var url = 'your api url';
$.ajax({
'url': yql_url,
'data': {
'q': 'SELECT * FROM json WHERE url="'+url+'"',
'format': 'json',
'jsonCompat': 'new',
},
'dataType': 'jsonp',
'success': function(response) {
console.log(response);
},
});
Here's the link with an explanation: https://vverma.net/fetch-any-json-using-jsonp-and-yql.html
You can bypass the problem by using YQL to proxy the request through Yahoo's servers. It is just a few lines of code:
var yql_url = 'https://query.yahooapis.com/v1/public/yql';
var url = 'your api url';
$.ajax({
'url': yql_url,
'data': {
'q': 'SELECT * FROM json WHERE url="'+url+'"',
'format': 'json',
'jsonCompat': 'new',
},
'dataType': 'jsonp',
'success': function(response) {
console.log(response);
},
});
Here's the link with an explanation: https://vverma.net/fetch-any-json-using-jsonp-and-yql.html
edited May 21 '17 at 11:39
Peter Mortensen
13.8k1987113
13.8k1987113
answered Nov 21 '16 at 14:59
camnesiacamnesia
379311
379311
but after seconds ... all the other codes run then it initialize.
– saber tabatabaee yazdi
Jun 8 '17 at 16:16
add a comment |
but after seconds ... all the other codes run then it initialize.
– saber tabatabaee yazdi
Jun 8 '17 at 16:16
but after seconds ... all the other codes run then it initialize.
– saber tabatabaee yazdi
Jun 8 '17 at 16:16
but after seconds ... all the other codes run then it initialize.
– saber tabatabaee yazdi
Jun 8 '17 at 16:16
add a comment |
If you are using Entity Framework, it seems that this error will sometimes be thrown even if you have CORS
enabled. I figured out that the error occurred because of a missing finalization of the query. I'm hoping this will help others in the same situation.
The following code can throw the XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource.
error:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
});
}
To fix it, a finalization call like .ToList()
or .FirstOrDefault()
at the end of the query is required, like so:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
}).ToList();
}
1
That seems like just an error that will happen in any application of entity framework if you don't finalize the query. Not really related to CORS or the OP's question.
– Gary
Jan 4 '16 at 21:20
2
It may very well not be related to CORS, but it throws an error that sounds like it has something to do with CORS; hence my answer.
– Loyalar
Feb 17 '16 at 6:52
add a comment |
If you are using Entity Framework, it seems that this error will sometimes be thrown even if you have CORS
enabled. I figured out that the error occurred because of a missing finalization of the query. I'm hoping this will help others in the same situation.
The following code can throw the XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource.
error:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
});
}
To fix it, a finalization call like .ToList()
or .FirstOrDefault()
at the end of the query is required, like so:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
}).ToList();
}
1
That seems like just an error that will happen in any application of entity framework if you don't finalize the query. Not really related to CORS or the OP's question.
– Gary
Jan 4 '16 at 21:20
2
It may very well not be related to CORS, but it throws an error that sounds like it has something to do with CORS; hence my answer.
– Loyalar
Feb 17 '16 at 6:52
add a comment |
If you are using Entity Framework, it seems that this error will sometimes be thrown even if you have CORS
enabled. I figured out that the error occurred because of a missing finalization of the query. I'm hoping this will help others in the same situation.
The following code can throw the XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource.
error:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
});
}
To fix it, a finalization call like .ToList()
or .FirstOrDefault()
at the end of the query is required, like so:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
}).ToList();
}
If you are using Entity Framework, it seems that this error will sometimes be thrown even if you have CORS
enabled. I figured out that the error occurred because of a missing finalization of the query. I'm hoping this will help others in the same situation.
The following code can throw the XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource.
error:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
});
}
To fix it, a finalization call like .ToList()
or .FirstOrDefault()
at the end of the query is required, like so:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
}).ToList();
}
edited Feb 16 '16 at 23:55
Peter Mortensen
13.8k1987113
13.8k1987113
answered Nov 3 '15 at 8:00
LoyalarLoyalar
1,55332040
1,55332040
1
That seems like just an error that will happen in any application of entity framework if you don't finalize the query. Not really related to CORS or the OP's question.
– Gary
Jan 4 '16 at 21:20
2
It may very well not be related to CORS, but it throws an error that sounds like it has something to do with CORS; hence my answer.
– Loyalar
Feb 17 '16 at 6:52
add a comment |
1
That seems like just an error that will happen in any application of entity framework if you don't finalize the query. Not really related to CORS or the OP's question.
– Gary
Jan 4 '16 at 21:20
2
It may very well not be related to CORS, but it throws an error that sounds like it has something to do with CORS; hence my answer.
– Loyalar
Feb 17 '16 at 6:52
1
1
That seems like just an error that will happen in any application of entity framework if you don't finalize the query. Not really related to CORS or the OP's question.
– Gary
Jan 4 '16 at 21:20
That seems like just an error that will happen in any application of entity framework if you don't finalize the query. Not really related to CORS or the OP's question.
– Gary
Jan 4 '16 at 21:20
2
2
It may very well not be related to CORS, but it throws an error that sounds like it has something to do with CORS; hence my answer.
– Loyalar
Feb 17 '16 at 6:52
It may very well not be related to CORS, but it throws an error that sounds like it has something to do with CORS; hence my answer.
– Loyalar
Feb 17 '16 at 6:52
add a comment |
In my case I was using JEE7 JAX-RS application and following tricks worked perfectly for me:
@GET
@Path("{id}")
public Response getEventData(@PathParam("id") String id) throws FileNotFoundException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/eventdata/" + id + ".json");
JsonReader jsonReader = Json.createReader(inputStream);
return Response.ok(jsonReader.readObject()).header("Access-Control-Allow-Origin", "*").build();
}
add a comment |
In my case I was using JEE7 JAX-RS application and following tricks worked perfectly for me:
@GET
@Path("{id}")
public Response getEventData(@PathParam("id") String id) throws FileNotFoundException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/eventdata/" + id + ".json");
JsonReader jsonReader = Json.createReader(inputStream);
return Response.ok(jsonReader.readObject()).header("Access-Control-Allow-Origin", "*").build();
}
add a comment |
In my case I was using JEE7 JAX-RS application and following tricks worked perfectly for me:
@GET
@Path("{id}")
public Response getEventData(@PathParam("id") String id) throws FileNotFoundException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/eventdata/" + id + ".json");
JsonReader jsonReader = Json.createReader(inputStream);
return Response.ok(jsonReader.readObject()).header("Access-Control-Allow-Origin", "*").build();
}
In my case I was using JEE7 JAX-RS application and following tricks worked perfectly for me:
@GET
@Path("{id}")
public Response getEventData(@PathParam("id") String id) throws FileNotFoundException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/eventdata/" + id + ".json");
JsonReader jsonReader = Json.createReader(inputStream);
return Response.ok(jsonReader.readObject()).header("Access-Control-Allow-Origin", "*").build();
}
answered Aug 13 '16 at 16:40
Bhuwan GautamBhuwan Gautam
7561720
7561720
add a comment |
add a comment |
I was successfully able to solve (in my case for fonts) using htaccess but obviously, OP is asking little different. But you can use FileMatch pattern and add any sort of extension so that it won't give cros error.
<IfModule mod_headers.c>
<FilesMatch ".(ttf|ttc|otf|eot|woff|woff2|font.css|css)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
https://httpd.apache.org/docs/2.4/mod/core.html#filesmatch
add a comment |
I was successfully able to solve (in my case for fonts) using htaccess but obviously, OP is asking little different. But you can use FileMatch pattern and add any sort of extension so that it won't give cros error.
<IfModule mod_headers.c>
<FilesMatch ".(ttf|ttc|otf|eot|woff|woff2|font.css|css)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
https://httpd.apache.org/docs/2.4/mod/core.html#filesmatch
add a comment |
I was successfully able to solve (in my case for fonts) using htaccess but obviously, OP is asking little different. But you can use FileMatch pattern and add any sort of extension so that it won't give cros error.
<IfModule mod_headers.c>
<FilesMatch ".(ttf|ttc|otf|eot|woff|woff2|font.css|css)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
https://httpd.apache.org/docs/2.4/mod/core.html#filesmatch
I was successfully able to solve (in my case for fonts) using htaccess but obviously, OP is asking little different. But you can use FileMatch pattern and add any sort of extension so that it won't give cros error.
<IfModule mod_headers.c>
<FilesMatch ".(ttf|ttc|otf|eot|woff|woff2|font.css|css)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
https://httpd.apache.org/docs/2.4/mod/core.html#filesmatch
answered Jun 15 '17 at 8:39
DanishDanish
804921
804921
add a comment |
add a comment |
Popular question -- Another thing to look at if you've read this far and nothing else has helped. If you have a CDN such as Akamai, Limelight or similar, you might want to check the cache key you have for the URI of the resource. If it does not include the Origin header value you may be returning a response cached when requested from another Origin. We just spent half a day debugging this. The CDN configuration was updated to only include the Origin value for a few select domains that are ours and set it to null for all others. This seems to work and allows browsers from our known domains to view our resources. Certainly all the other answers are prerequisites to getting here but if the CDN is the first hop from your browser this is something to review.
In our case we could see some requests making it to our service but not nearly the volume the site was sending. That pointed us to the CDN. We were able to go back and see the original request was served from a direct request, not part of a browser AJAX call and the response header Access-Control-Allow-Origin was not included. Apparently the CDN cached this value. The Akamai CDN configuration tweak to consider the Origin request header value as part of the match seems to have made it work for us.
1
In your case, wouldn’t sending theVary: Origin
response header have achieved the same effect? stackoverflow.com/questions/46063304/…
– sideshowbarker
Sep 7 '17 at 21:19
2
Yes but we don't. A service exposed to the world can be DOS'ed via cache explosion by sending bogus values. Akamai has some help in this area to reduce DOS exposure. My point is that you can do everything listed and still have a problem because of caching.
– No Refunds No Returns
Sep 7 '17 at 22:42
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:39
@Quentin You are so RIGHT! however this is the #1 hit for many searches on this topic, there are already a variety of answers that vary from the exact question yet provide useful information AND this was what we discovered on Sept 7 after exhausting all of the threads. I appreciate your downvote. Future readers will be also able be able to weigh whether or not this "not an answer" was helpful by voting, perhaps even differently from you. There is at least one other person who has already publicly disagreed with your opinion. Will be interesting to see how the voting goes from here........
– No Refunds No Returns
Sep 13 '17 at 14:54
+5/-1 Thanks again masses.
– No Refunds No Returns
Aug 21 '18 at 17:42
add a comment |
Popular question -- Another thing to look at if you've read this far and nothing else has helped. If you have a CDN such as Akamai, Limelight or similar, you might want to check the cache key you have for the URI of the resource. If it does not include the Origin header value you may be returning a response cached when requested from another Origin. We just spent half a day debugging this. The CDN configuration was updated to only include the Origin value for a few select domains that are ours and set it to null for all others. This seems to work and allows browsers from our known domains to view our resources. Certainly all the other answers are prerequisites to getting here but if the CDN is the first hop from your browser this is something to review.
In our case we could see some requests making it to our service but not nearly the volume the site was sending. That pointed us to the CDN. We were able to go back and see the original request was served from a direct request, not part of a browser AJAX call and the response header Access-Control-Allow-Origin was not included. Apparently the CDN cached this value. The Akamai CDN configuration tweak to consider the Origin request header value as part of the match seems to have made it work for us.
1
In your case, wouldn’t sending theVary: Origin
response header have achieved the same effect? stackoverflow.com/questions/46063304/…
– sideshowbarker
Sep 7 '17 at 21:19
2
Yes but we don't. A service exposed to the world can be DOS'ed via cache explosion by sending bogus values. Akamai has some help in this area to reduce DOS exposure. My point is that you can do everything listed and still have a problem because of caching.
– No Refunds No Returns
Sep 7 '17 at 22:42
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:39
@Quentin You are so RIGHT! however this is the #1 hit for many searches on this topic, there are already a variety of answers that vary from the exact question yet provide useful information AND this was what we discovered on Sept 7 after exhausting all of the threads. I appreciate your downvote. Future readers will be also able be able to weigh whether or not this "not an answer" was helpful by voting, perhaps even differently from you. There is at least one other person who has already publicly disagreed with your opinion. Will be interesting to see how the voting goes from here........
– No Refunds No Returns
Sep 13 '17 at 14:54
+5/-1 Thanks again masses.
– No Refunds No Returns
Aug 21 '18 at 17:42
add a comment |
Popular question -- Another thing to look at if you've read this far and nothing else has helped. If you have a CDN such as Akamai, Limelight or similar, you might want to check the cache key you have for the URI of the resource. If it does not include the Origin header value you may be returning a response cached when requested from another Origin. We just spent half a day debugging this. The CDN configuration was updated to only include the Origin value for a few select domains that are ours and set it to null for all others. This seems to work and allows browsers from our known domains to view our resources. Certainly all the other answers are prerequisites to getting here but if the CDN is the first hop from your browser this is something to review.
In our case we could see some requests making it to our service but not nearly the volume the site was sending. That pointed us to the CDN. We were able to go back and see the original request was served from a direct request, not part of a browser AJAX call and the response header Access-Control-Allow-Origin was not included. Apparently the CDN cached this value. The Akamai CDN configuration tweak to consider the Origin request header value as part of the match seems to have made it work for us.
Popular question -- Another thing to look at if you've read this far and nothing else has helped. If you have a CDN such as Akamai, Limelight or similar, you might want to check the cache key you have for the URI of the resource. If it does not include the Origin header value you may be returning a response cached when requested from another Origin. We just spent half a day debugging this. The CDN configuration was updated to only include the Origin value for a few select domains that are ours and set it to null for all others. This seems to work and allows browsers from our known domains to view our resources. Certainly all the other answers are prerequisites to getting here but if the CDN is the first hop from your browser this is something to review.
In our case we could see some requests making it to our service but not nearly the volume the site was sending. That pointed us to the CDN. We were able to go back and see the original request was served from a direct request, not part of a browser AJAX call and the response header Access-Control-Allow-Origin was not included. Apparently the CDN cached this value. The Akamai CDN configuration tweak to consider the Origin request header value as part of the match seems to have made it work for us.
edited Dec 28 '17 at 1:11
answered Sep 7 '17 at 14:49
No Refunds No ReturnsNo Refunds No Returns
5,53441936
5,53441936
1
In your case, wouldn’t sending theVary: Origin
response header have achieved the same effect? stackoverflow.com/questions/46063304/…
– sideshowbarker
Sep 7 '17 at 21:19
2
Yes but we don't. A service exposed to the world can be DOS'ed via cache explosion by sending bogus values. Akamai has some help in this area to reduce DOS exposure. My point is that you can do everything listed and still have a problem because of caching.
– No Refunds No Returns
Sep 7 '17 at 22:42
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:39
@Quentin You are so RIGHT! however this is the #1 hit for many searches on this topic, there are already a variety of answers that vary from the exact question yet provide useful information AND this was what we discovered on Sept 7 after exhausting all of the threads. I appreciate your downvote. Future readers will be also able be able to weigh whether or not this "not an answer" was helpful by voting, perhaps even differently from you. There is at least one other person who has already publicly disagreed with your opinion. Will be interesting to see how the voting goes from here........
– No Refunds No Returns
Sep 13 '17 at 14:54
+5/-1 Thanks again masses.
– No Refunds No Returns
Aug 21 '18 at 17:42
add a comment |
1
In your case, wouldn’t sending theVary: Origin
response header have achieved the same effect? stackoverflow.com/questions/46063304/…
– sideshowbarker
Sep 7 '17 at 21:19
2
Yes but we don't. A service exposed to the world can be DOS'ed via cache explosion by sending bogus values. Akamai has some help in this area to reduce DOS exposure. My point is that you can do everything listed and still have a problem because of caching.
– No Refunds No Returns
Sep 7 '17 at 22:42
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:39
@Quentin You are so RIGHT! however this is the #1 hit for many searches on this topic, there are already a variety of answers that vary from the exact question yet provide useful information AND this was what we discovered on Sept 7 after exhausting all of the threads. I appreciate your downvote. Future readers will be also able be able to weigh whether or not this "not an answer" was helpful by voting, perhaps even differently from you. There is at least one other person who has already publicly disagreed with your opinion. Will be interesting to see how the voting goes from here........
– No Refunds No Returns
Sep 13 '17 at 14:54
+5/-1 Thanks again masses.
– No Refunds No Returns
Aug 21 '18 at 17:42
1
1
In your case, wouldn’t sending the
Vary: Origin
response header have achieved the same effect? stackoverflow.com/questions/46063304/…– sideshowbarker
Sep 7 '17 at 21:19
In your case, wouldn’t sending the
Vary: Origin
response header have achieved the same effect? stackoverflow.com/questions/46063304/…– sideshowbarker
Sep 7 '17 at 21:19
2
2
Yes but we don't. A service exposed to the world can be DOS'ed via cache explosion by sending bogus values. Akamai has some help in this area to reduce DOS exposure. My point is that you can do everything listed and still have a problem because of caching.
– No Refunds No Returns
Sep 7 '17 at 22:42
Yes but we don't. A service exposed to the world can be DOS'ed via cache explosion by sending bogus values. Akamai has some help in this area to reduce DOS exposure. My point is that you can do everything listed and still have a problem because of caching.
– No Refunds No Returns
Sep 7 '17 at 22:42
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:39
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:39
@Quentin You are so RIGHT! however this is the #1 hit for many searches on this topic, there are already a variety of answers that vary from the exact question yet provide useful information AND this was what we discovered on Sept 7 after exhausting all of the threads. I appreciate your downvote. Future readers will be also able be able to weigh whether or not this "not an answer" was helpful by voting, perhaps even differently from you. There is at least one other person who has already publicly disagreed with your opinion. Will be interesting to see how the voting goes from here........
– No Refunds No Returns
Sep 13 '17 at 14:54
@Quentin You are so RIGHT! however this is the #1 hit for many searches on this topic, there are already a variety of answers that vary from the exact question yet provide useful information AND this was what we discovered on Sept 7 after exhausting all of the threads. I appreciate your downvote. Future readers will be also able be able to weigh whether or not this "not an answer" was helpful by voting, perhaps even differently from you. There is at least one other person who has already publicly disagreed with your opinion. Will be interesting to see how the voting goes from here........
– No Refunds No Returns
Sep 13 '17 at 14:54
+5/-1 Thanks again masses.
– No Refunds No Returns
Aug 21 '18 at 17:42
+5/-1 Thanks again masses.
– No Refunds No Returns
Aug 21 '18 at 17:42
add a comment |
For the GoLang API:
First you can take a look at MDN CORS Doc to know what CORS is. As far as I know, CORS is about whether to allow Origin Of Request to access Server Resource or not.
And you can restrict which request origin can access the server by setting Access-Control-Allow-Origin
at Header
of Server Response.
For example, Setting following header in Server Response means that only request sent from http://foo.example
can access your server:
Access-Control-Allow-Origin: http://foo.example
and following allow request sent from any origin(or domain):
Access-Control-Allow-Origin: *
And as I know in the error message, requested resource
means resource of server, so No 'Access-Control-Allow-Origin' header is present on the requested resource.
means you didn't set Access-Control-Allow-Origin
header in your Server Response, or maybe you set but the origin of request isn't list in Access-Control-Allow-Origin
so request is not allowed access:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
In GoLang, I use gorilla/mux
package to build API server at localhost:9091
, and I allow CORS by add "Access-Control-Allow-Origin", "*"
to header of response:
func main() { // API Server Code
router := mux.NewRouter()
// API route is /people,
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeople).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))
}
// Method of '/people' route
func GetPeople(w http.ResponseWriter, r *http.Request) {
// Allow CORS by setting * in sever response
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
json.NewEncoder(w).Encode("OKOK")
}
And I use JavaScript in the client, at localhost:9092
make request by Chrome can succesfully get "OKOK" from Server localhost:9091
.
function GetPeople() {
try {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:9091/people", false);
xhttp.setRequestHeader("Content-type", "text/html");
xhttp.send();
var response = JSON.parse(xhttp.response);
alert(xhttp.response);
}
catch (error) {
alert(error.message);
}
}
Besides you can check your request/response header by tools like Fiddler
.
add a comment |
For the GoLang API:
First you can take a look at MDN CORS Doc to know what CORS is. As far as I know, CORS is about whether to allow Origin Of Request to access Server Resource or not.
And you can restrict which request origin can access the server by setting Access-Control-Allow-Origin
at Header
of Server Response.
For example, Setting following header in Server Response means that only request sent from http://foo.example
can access your server:
Access-Control-Allow-Origin: http://foo.example
and following allow request sent from any origin(or domain):
Access-Control-Allow-Origin: *
And as I know in the error message, requested resource
means resource of server, so No 'Access-Control-Allow-Origin' header is present on the requested resource.
means you didn't set Access-Control-Allow-Origin
header in your Server Response, or maybe you set but the origin of request isn't list in Access-Control-Allow-Origin
so request is not allowed access:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
In GoLang, I use gorilla/mux
package to build API server at localhost:9091
, and I allow CORS by add "Access-Control-Allow-Origin", "*"
to header of response:
func main() { // API Server Code
router := mux.NewRouter()
// API route is /people,
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeople).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))
}
// Method of '/people' route
func GetPeople(w http.ResponseWriter, r *http.Request) {
// Allow CORS by setting * in sever response
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
json.NewEncoder(w).Encode("OKOK")
}
And I use JavaScript in the client, at localhost:9092
make request by Chrome can succesfully get "OKOK" from Server localhost:9091
.
function GetPeople() {
try {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:9091/people", false);
xhttp.setRequestHeader("Content-type", "text/html");
xhttp.send();
var response = JSON.parse(xhttp.response);
alert(xhttp.response);
}
catch (error) {
alert(error.message);
}
}
Besides you can check your request/response header by tools like Fiddler
.
add a comment |
For the GoLang API:
First you can take a look at MDN CORS Doc to know what CORS is. As far as I know, CORS is about whether to allow Origin Of Request to access Server Resource or not.
And you can restrict which request origin can access the server by setting Access-Control-Allow-Origin
at Header
of Server Response.
For example, Setting following header in Server Response means that only request sent from http://foo.example
can access your server:
Access-Control-Allow-Origin: http://foo.example
and following allow request sent from any origin(or domain):
Access-Control-Allow-Origin: *
And as I know in the error message, requested resource
means resource of server, so No 'Access-Control-Allow-Origin' header is present on the requested resource.
means you didn't set Access-Control-Allow-Origin
header in your Server Response, or maybe you set but the origin of request isn't list in Access-Control-Allow-Origin
so request is not allowed access:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
In GoLang, I use gorilla/mux
package to build API server at localhost:9091
, and I allow CORS by add "Access-Control-Allow-Origin", "*"
to header of response:
func main() { // API Server Code
router := mux.NewRouter()
// API route is /people,
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeople).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))
}
// Method of '/people' route
func GetPeople(w http.ResponseWriter, r *http.Request) {
// Allow CORS by setting * in sever response
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
json.NewEncoder(w).Encode("OKOK")
}
And I use JavaScript in the client, at localhost:9092
make request by Chrome can succesfully get "OKOK" from Server localhost:9091
.
function GetPeople() {
try {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:9091/people", false);
xhttp.setRequestHeader("Content-type", "text/html");
xhttp.send();
var response = JSON.parse(xhttp.response);
alert(xhttp.response);
}
catch (error) {
alert(error.message);
}
}
Besides you can check your request/response header by tools like Fiddler
.
For the GoLang API:
First you can take a look at MDN CORS Doc to know what CORS is. As far as I know, CORS is about whether to allow Origin Of Request to access Server Resource or not.
And you can restrict which request origin can access the server by setting Access-Control-Allow-Origin
at Header
of Server Response.
For example, Setting following header in Server Response means that only request sent from http://foo.example
can access your server:
Access-Control-Allow-Origin: http://foo.example
and following allow request sent from any origin(or domain):
Access-Control-Allow-Origin: *
And as I know in the error message, requested resource
means resource of server, so No 'Access-Control-Allow-Origin' header is present on the requested resource.
means you didn't set Access-Control-Allow-Origin
header in your Server Response, or maybe you set but the origin of request isn't list in Access-Control-Allow-Origin
so request is not allowed access:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
In GoLang, I use gorilla/mux
package to build API server at localhost:9091
, and I allow CORS by add "Access-Control-Allow-Origin", "*"
to header of response:
func main() { // API Server Code
router := mux.NewRouter()
// API route is /people,
//Methods("GET", "OPTIONS") means it support GET, OPTIONS
router.HandleFunc("/people", GetPeople).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":9091", router))
}
// Method of '/people' route
func GetPeople(w http.ResponseWriter, r *http.Request) {
// Allow CORS by setting * in sever response
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
json.NewEncoder(w).Encode("OKOK")
}
And I use JavaScript in the client, at localhost:9092
make request by Chrome can succesfully get "OKOK" from Server localhost:9091
.
function GetPeople() {
try {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:9091/people", false);
xhttp.setRequestHeader("Content-type", "text/html");
xhttp.send();
var response = JSON.parse(xhttp.response);
alert(xhttp.response);
}
catch (error) {
alert(error.message);
}
}
Besides you can check your request/response header by tools like Fiddler
.
edited Mar 21 '18 at 18:22
Peter Mortensen
13.8k1987113
13.8k1987113
answered Nov 19 '17 at 12:19
yu yang Jianyu yang Jian
2,52722341
2,52722341
add a comment |
add a comment |
If you get this error message from the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:
<?php header('Access-Control-Allow-Origin: *'); ?>
You really need, especially if you only use JavaScript to do the Ajax request, an internal proxy who takes your query and sends it through to the remote server.
First in your JavaScript code, do an Ajax call to your own server, something like:
$.ajax({
url: yourserver.com/controller/proxy.php,
async: false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:
if (isset($_POST)) {
$apiKey = $_POST['apiKey'];
$cid = $_POST['cid'];
$minorRev = 99;
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;
echo json_encode(file_get_contents($url));
}
By doing:
echo json_encode(file_get_contents($url));
You are just doing the same query, but on the server side and after that, it should work fine.
Answer copied and pasted from NizarBsb
@NizarBsb's answer link is here No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
– tech_me
Jun 6 '18 at 13:04
This is a big security risk!
– Stephan Weinhold
Jun 9 '18 at 20:14
@stephan-weinhold in case you would actually sanitize the url parameters. would it still be a security risk? why?
– mwallisch
Jun 13 '18 at 11:15
add a comment |
If you get this error message from the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:
<?php header('Access-Control-Allow-Origin: *'); ?>
You really need, especially if you only use JavaScript to do the Ajax request, an internal proxy who takes your query and sends it through to the remote server.
First in your JavaScript code, do an Ajax call to your own server, something like:
$.ajax({
url: yourserver.com/controller/proxy.php,
async: false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:
if (isset($_POST)) {
$apiKey = $_POST['apiKey'];
$cid = $_POST['cid'];
$minorRev = 99;
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;
echo json_encode(file_get_contents($url));
}
By doing:
echo json_encode(file_get_contents($url));
You are just doing the same query, but on the server side and after that, it should work fine.
Answer copied and pasted from NizarBsb
@NizarBsb's answer link is here No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
– tech_me
Jun 6 '18 at 13:04
This is a big security risk!
– Stephan Weinhold
Jun 9 '18 at 20:14
@stephan-weinhold in case you would actually sanitize the url parameters. would it still be a security risk? why?
– mwallisch
Jun 13 '18 at 11:15
add a comment |
If you get this error message from the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:
<?php header('Access-Control-Allow-Origin: *'); ?>
You really need, especially if you only use JavaScript to do the Ajax request, an internal proxy who takes your query and sends it through to the remote server.
First in your JavaScript code, do an Ajax call to your own server, something like:
$.ajax({
url: yourserver.com/controller/proxy.php,
async: false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:
if (isset($_POST)) {
$apiKey = $_POST['apiKey'];
$cid = $_POST['cid'];
$minorRev = 99;
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;
echo json_encode(file_get_contents($url));
}
By doing:
echo json_encode(file_get_contents($url));
You are just doing the same query, but on the server side and after that, it should work fine.
Answer copied and pasted from NizarBsb
If you get this error message from the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:
<?php header('Access-Control-Allow-Origin: *'); ?>
You really need, especially if you only use JavaScript to do the Ajax request, an internal proxy who takes your query and sends it through to the remote server.
First in your JavaScript code, do an Ajax call to your own server, something like:
$.ajax({
url: yourserver.com/controller/proxy.php,
async: false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:
if (isset($_POST)) {
$apiKey = $_POST['apiKey'];
$cid = $_POST['cid'];
$minorRev = 99;
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;
echo json_encode(file_get_contents($url));
}
By doing:
echo json_encode(file_get_contents($url));
You are just doing the same query, but on the server side and after that, it should work fine.
Answer copied and pasted from NizarBsb
edited Mar 21 '18 at 18:25
Peter Mortensen
13.8k1987113
13.8k1987113
answered Oct 26 '17 at 13:23
FlashFlash
688710
688710
@NizarBsb's answer link is here No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
– tech_me
Jun 6 '18 at 13:04
This is a big security risk!
– Stephan Weinhold
Jun 9 '18 at 20:14
@stephan-weinhold in case you would actually sanitize the url parameters. would it still be a security risk? why?
– mwallisch
Jun 13 '18 at 11:15
add a comment |
@NizarBsb's answer link is here No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
– tech_me
Jun 6 '18 at 13:04
This is a big security risk!
– Stephan Weinhold
Jun 9 '18 at 20:14
@stephan-weinhold in case you would actually sanitize the url parameters. would it still be a security risk? why?
– mwallisch
Jun 13 '18 at 11:15
@NizarBsb's answer link is here No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
– tech_me
Jun 6 '18 at 13:04
@NizarBsb's answer link is here No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
– tech_me
Jun 6 '18 at 13:04
This is a big security risk!
– Stephan Weinhold
Jun 9 '18 at 20:14
This is a big security risk!
– Stephan Weinhold
Jun 9 '18 at 20:14
@stephan-weinhold in case you would actually sanitize the url parameters. would it still be a security risk? why?
– mwallisch
Jun 13 '18 at 11:15
@stephan-weinhold in case you would actually sanitize the url parameters. would it still be a security risk? why?
– mwallisch
Jun 13 '18 at 11:15
add a comment |
A lot of times this happens to me from javascript to my php api, because one of a few reasons.
I forget to put the <?php header('Access-Control-Allow-Origin: *'); ?
is one. This is helpful for cross sub domain access. Another reason, is because in jQuery ajax request I am specifying a specific dataType and returning a different dataType, so it throws an error.
The Last and most prominent reasoning for this error is there is a parse error on the page you are requesting. If you hit that page url in your browser than more than likely you will see a parse error and you will have a line number to address the issue.
I hope this helps someone. It took me a while each time to debug this and I wish I had a checklist of things to verify.
add a comment |
A lot of times this happens to me from javascript to my php api, because one of a few reasons.
I forget to put the <?php header('Access-Control-Allow-Origin: *'); ?
is one. This is helpful for cross sub domain access. Another reason, is because in jQuery ajax request I am specifying a specific dataType and returning a different dataType, so it throws an error.
The Last and most prominent reasoning for this error is there is a parse error on the page you are requesting. If you hit that page url in your browser than more than likely you will see a parse error and you will have a line number to address the issue.
I hope this helps someone. It took me a while each time to debug this and I wish I had a checklist of things to verify.
add a comment |
A lot of times this happens to me from javascript to my php api, because one of a few reasons.
I forget to put the <?php header('Access-Control-Allow-Origin: *'); ?
is one. This is helpful for cross sub domain access. Another reason, is because in jQuery ajax request I am specifying a specific dataType and returning a different dataType, so it throws an error.
The Last and most prominent reasoning for this error is there is a parse error on the page you are requesting. If you hit that page url in your browser than more than likely you will see a parse error and you will have a line number to address the issue.
I hope this helps someone. It took me a while each time to debug this and I wish I had a checklist of things to verify.
A lot of times this happens to me from javascript to my php api, because one of a few reasons.
I forget to put the <?php header('Access-Control-Allow-Origin: *'); ?
is one. This is helpful for cross sub domain access. Another reason, is because in jQuery ajax request I am specifying a specific dataType and returning a different dataType, so it throws an error.
The Last and most prominent reasoning for this error is there is a parse error on the page you are requesting. If you hit that page url in your browser than more than likely you will see a parse error and you will have a line number to address the issue.
I hope this helps someone. It took me a while each time to debug this and I wish I had a checklist of things to verify.
answered Mar 25 '16 at 20:54
Garrett TacoronteGarrett Tacoronte
38736
38736
add a comment |
add a comment |
I got this error with $http.get
in Angular. I needed to use $http.jsonp
instead.
add a comment |
I got this error with $http.get
in Angular. I needed to use $http.jsonp
instead.
add a comment |
I got this error with $http.get
in Angular. I needed to use $http.jsonp
instead.
I got this error with $http.get
in Angular. I needed to use $http.jsonp
instead.
edited May 21 '17 at 11:34
Peter Mortensen
13.8k1987113
13.8k1987113
answered Feb 13 '17 at 17:46
Travis HeeterTravis Heeter
4,89544477
4,89544477
add a comment |
add a comment |
On my website (based on .NET) I've just added this:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Big thanks to this video.
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
On my website (based on .NET) I've just added this:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Big thanks to this video.
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
On my website (based on .NET) I've just added this:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Big thanks to this video.
On my website (based on .NET) I've just added this:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Big thanks to this video.
answered Aug 19 '17 at 15:13
FrenkyBFrenkyB
2,26653363
2,26653363
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
1
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
CORS is for you.
CORS is "Cross Origin Resource Sharing" and is a way to send a cross-domain request. Now the XMLHttpRequest2 and Fetch API both support CORS.
But it has its limits. Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.
And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*').
For lots of request way if you don't know what to choose, I think you need a fully functional component to do that. Let me introduce a simple component catta
If you are using a modern browser (> Internet Explorer9, Chrome, Firefox, Edge, etc.), it is very recommended you use a simple, but beautiful component, https://github.com/Joker-Jelly/catta. It has no dependencies, is less than 3 KB, and it supports Fetch, Ajax and JSONP with same dead-simple syntax and options.
catta('./data/simple.json').then(function (res) {
console.log(res);
});
It also supports all the way to import to your project, like ES6 module, CommonJS and even <script>
in HTML.
I have an IIS site which is local that is hosting my API. I have an external site which is accessed outside the local network. I am trying to execute the API from the external site, I have CORS enabled for the external site (e.g.[EnableCors(origins: "http://websitelink.com", headers: "*", methods: "*")]
but it is not working. Any idea? forums.asp.net/p/2117965/…
– Si8
Mar 24 '17 at 14:12
add a comment |
CORS is for you.
CORS is "Cross Origin Resource Sharing" and is a way to send a cross-domain request. Now the XMLHttpRequest2 and Fetch API both support CORS.
But it has its limits. Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.
And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*').
For lots of request way if you don't know what to choose, I think you need a fully functional component to do that. Let me introduce a simple component catta
If you are using a modern browser (> Internet Explorer9, Chrome, Firefox, Edge, etc.), it is very recommended you use a simple, but beautiful component, https://github.com/Joker-Jelly/catta. It has no dependencies, is less than 3 KB, and it supports Fetch, Ajax and JSONP with same dead-simple syntax and options.
catta('./data/simple.json').then(function (res) {
console.log(res);
});
It also supports all the way to import to your project, like ES6 module, CommonJS and even <script>
in HTML.
I have an IIS site which is local that is hosting my API. I have an external site which is accessed outside the local network. I am trying to execute the API from the external site, I have CORS enabled for the external site (e.g.[EnableCors(origins: "http://websitelink.com", headers: "*", methods: "*")]
but it is not working. Any idea? forums.asp.net/p/2117965/…
– Si8
Mar 24 '17 at 14:12
add a comment |
CORS is for you.
CORS is "Cross Origin Resource Sharing" and is a way to send a cross-domain request. Now the XMLHttpRequest2 and Fetch API both support CORS.
But it has its limits. Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.
And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*').
For lots of request way if you don't know what to choose, I think you need a fully functional component to do that. Let me introduce a simple component catta
If you are using a modern browser (> Internet Explorer9, Chrome, Firefox, Edge, etc.), it is very recommended you use a simple, but beautiful component, https://github.com/Joker-Jelly/catta. It has no dependencies, is less than 3 KB, and it supports Fetch, Ajax and JSONP with same dead-simple syntax and options.
catta('./data/simple.json').then(function (res) {
console.log(res);
});
It also supports all the way to import to your project, like ES6 module, CommonJS and even <script>
in HTML.
CORS is for you.
CORS is "Cross Origin Resource Sharing" and is a way to send a cross-domain request. Now the XMLHttpRequest2 and Fetch API both support CORS.
But it has its limits. Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.
And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*').
For lots of request way if you don't know what to choose, I think you need a fully functional component to do that. Let me introduce a simple component catta
If you are using a modern browser (> Internet Explorer9, Chrome, Firefox, Edge, etc.), it is very recommended you use a simple, but beautiful component, https://github.com/Joker-Jelly/catta. It has no dependencies, is less than 3 KB, and it supports Fetch, Ajax and JSONP with same dead-simple syntax and options.
catta('./data/simple.json').then(function (res) {
console.log(res);
});
It also supports all the way to import to your project, like ES6 module, CommonJS and even <script>
in HTML.
edited Sep 23 '17 at 23:39
Peter Mortensen
13.8k1987113
13.8k1987113
answered Jan 19 '17 at 14:40
JellyJelly
37716
37716
I have an IIS site which is local that is hosting my API. I have an external site which is accessed outside the local network. I am trying to execute the API from the external site, I have CORS enabled for the external site (e.g.[EnableCors(origins: "http://websitelink.com", headers: "*", methods: "*")]
but it is not working. Any idea? forums.asp.net/p/2117965/…
– Si8
Mar 24 '17 at 14:12
add a comment |
I have an IIS site which is local that is hosting my API. I have an external site which is accessed outside the local network. I am trying to execute the API from the external site, I have CORS enabled for the external site (e.g.[EnableCors(origins: "http://websitelink.com", headers: "*", methods: "*")]
but it is not working. Any idea? forums.asp.net/p/2117965/…
– Si8
Mar 24 '17 at 14:12
I have an IIS site which is local that is hosting my API. I have an external site which is accessed outside the local network. I am trying to execute the API from the external site, I have CORS enabled for the external site (e.g.
[EnableCors(origins: "http://websitelink.com", headers: "*", methods: "*")]
but it is not working. Any idea? forums.asp.net/p/2117965/…– Si8
Mar 24 '17 at 14:12
I have an IIS site which is local that is hosting my API. I have an external site which is accessed outside the local network. I am trying to execute the API from the external site, I have CORS enabled for the external site (e.g.
[EnableCors(origins: "http://websitelink.com", headers: "*", methods: "*")]
but it is not working. Any idea? forums.asp.net/p/2117965/…– Si8
Mar 24 '17 at 14:12
add a comment |
Most of these answers tell users how to add CORS headers to a server they control.
However, if you need data from a server you don't control in a webpage, one solution is to create a script tag on your page, set the src attribute to the api endpoint that doesn't have CORS headers, then load that data onto the page:
window.handleData = function(data) {
console.log(data)
};
var script = document.createElement('script');
script.setAttribute('src','https://some.api/without/cors/headers.com&callback=handleData');
document.body.appendChild(script);
Excellent answer, but if script is not in correct format, then you can't reach its code (script.text= empty). What to do in this case? How to reach its code?
– Angel T
Feb 8 '18 at 6:52
How to prevent the execution of the script (maybe as comment it all)?
– Angel T
Feb 8 '18 at 7:16
And another interesting thing: Only IE11 with Enabled "Access data sources across domains" can access cross-domain (without of need to control server to modificate Origin!. All rest major browsers can't
– Angel T
Feb 8 '18 at 8:14
add a comment |
Most of these answers tell users how to add CORS headers to a server they control.
However, if you need data from a server you don't control in a webpage, one solution is to create a script tag on your page, set the src attribute to the api endpoint that doesn't have CORS headers, then load that data onto the page:
window.handleData = function(data) {
console.log(data)
};
var script = document.createElement('script');
script.setAttribute('src','https://some.api/without/cors/headers.com&callback=handleData');
document.body.appendChild(script);
Excellent answer, but if script is not in correct format, then you can't reach its code (script.text= empty). What to do in this case? How to reach its code?
– Angel T
Feb 8 '18 at 6:52
How to prevent the execution of the script (maybe as comment it all)?
– Angel T
Feb 8 '18 at 7:16
And another interesting thing: Only IE11 with Enabled "Access data sources across domains" can access cross-domain (without of need to control server to modificate Origin!. All rest major browsers can't
– Angel T
Feb 8 '18 at 8:14
add a comment |
Most of these answers tell users how to add CORS headers to a server they control.
However, if you need data from a server you don't control in a webpage, one solution is to create a script tag on your page, set the src attribute to the api endpoint that doesn't have CORS headers, then load that data onto the page:
window.handleData = function(data) {
console.log(data)
};
var script = document.createElement('script');
script.setAttribute('src','https://some.api/without/cors/headers.com&callback=handleData');
document.body.appendChild(script);
Most of these answers tell users how to add CORS headers to a server they control.
However, if you need data from a server you don't control in a webpage, one solution is to create a script tag on your page, set the src attribute to the api endpoint that doesn't have CORS headers, then load that data onto the page:
window.handleData = function(data) {
console.log(data)
};
var script = document.createElement('script');
script.setAttribute('src','https://some.api/without/cors/headers.com&callback=handleData');
document.body.appendChild(script);
answered Jan 31 '18 at 15:13
duhaimeduhaime
8,97555986
8,97555986
Excellent answer, but if script is not in correct format, then you can't reach its code (script.text= empty). What to do in this case? How to reach its code?
– Angel T
Feb 8 '18 at 6:52
How to prevent the execution of the script (maybe as comment it all)?
– Angel T
Feb 8 '18 at 7:16
And another interesting thing: Only IE11 with Enabled "Access data sources across domains" can access cross-domain (without of need to control server to modificate Origin!. All rest major browsers can't
– Angel T
Feb 8 '18 at 8:14
add a comment |
Excellent answer, but if script is not in correct format, then you can't reach its code (script.text= empty). What to do in this case? How to reach its code?
– Angel T
Feb 8 '18 at 6:52
How to prevent the execution of the script (maybe as comment it all)?
– Angel T
Feb 8 '18 at 7:16
And another interesting thing: Only IE11 with Enabled "Access data sources across domains" can access cross-domain (without of need to control server to modificate Origin!. All rest major browsers can't
– Angel T
Feb 8 '18 at 8:14
Excellent answer, but if script is not in correct format, then you can't reach its code (script.text= empty). What to do in this case? How to reach its code?
– Angel T
Feb 8 '18 at 6:52
Excellent answer, but if script is not in correct format, then you can't reach its code (script.text= empty). What to do in this case? How to reach its code?
– Angel T
Feb 8 '18 at 6:52
How to prevent the execution of the script (maybe as comment it all)?
– Angel T
Feb 8 '18 at 7:16
How to prevent the execution of the script (maybe as comment it all)?
– Angel T
Feb 8 '18 at 7:16
And another interesting thing: Only IE11 with Enabled "Access data sources across domains" can access cross-domain (without of need to control server to modificate Origin!. All rest major browsers can't
– Angel T
Feb 8 '18 at 8:14
And another interesting thing: Only IE11 with Enabled "Access data sources across domains" can access cross-domain (without of need to control server to modificate Origin!. All rest major browsers can't
– Angel T
Feb 8 '18 at 8:14
add a comment |
For completeness, Apache allows cors:
Header set Access-Control-Allow-Origin "http://www.allowonlyfromthisurl.com"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, Accept-Encoding, Accept-Language, Cookie, Referer"
Anybody can add to that ^
– zak
Nov 20 '17 at 0:05
Worked for Apache and laravel 5.4
– Rohit Dhiman
Sep 18 '18 at 6:56
add a comment |
For completeness, Apache allows cors:
Header set Access-Control-Allow-Origin "http://www.allowonlyfromthisurl.com"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, Accept-Encoding, Accept-Language, Cookie, Referer"
Anybody can add to that ^
– zak
Nov 20 '17 at 0:05
Worked for Apache and laravel 5.4
– Rohit Dhiman
Sep 18 '18 at 6:56
add a comment |
For completeness, Apache allows cors:
Header set Access-Control-Allow-Origin "http://www.allowonlyfromthisurl.com"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, Accept-Encoding, Accept-Language, Cookie, Referer"
For completeness, Apache allows cors:
Header set Access-Control-Allow-Origin "http://www.allowonlyfromthisurl.com"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, Accept-Encoding, Accept-Language, Cookie, Referer"
edited Mar 21 '18 at 18:19
Peter Mortensen
13.8k1987113
13.8k1987113
answered Nov 20 '17 at 0:05
zakzak
1484
1484
Anybody can add to that ^
– zak
Nov 20 '17 at 0:05
Worked for Apache and laravel 5.4
– Rohit Dhiman
Sep 18 '18 at 6:56
add a comment |
Anybody can add to that ^
– zak
Nov 20 '17 at 0:05
Worked for Apache and laravel 5.4
– Rohit Dhiman
Sep 18 '18 at 6:56
Anybody can add to that ^
– zak
Nov 20 '17 at 0:05
Anybody can add to that ^
– zak
Nov 20 '17 at 0:05
Worked for Apache and laravel 5.4
– Rohit Dhiman
Sep 18 '18 at 6:56
Worked for Apache and laravel 5.4
– Rohit Dhiman
Sep 18 '18 at 6:56
add a comment |
In jsonp request you should catch "jsonpCallback" and send him back.
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
On backend side (if you use as backend PHP)
echo $_GET['callback'].'({"ip":"192.168.1.1"})';
In this case backend response seems like
jQuery331009526199802841284_1533646326884({"ip":"192.168.1.1"})
but you can set a "jsonpCallback" manually on frontend and catch him on backend side
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'get_ip',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
In this case backend response seems like
get_ip({"ip":"192.168.1.1"})
add a comment |
In jsonp request you should catch "jsonpCallback" and send him back.
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
On backend side (if you use as backend PHP)
echo $_GET['callback'].'({"ip":"192.168.1.1"})';
In this case backend response seems like
jQuery331009526199802841284_1533646326884({"ip":"192.168.1.1"})
but you can set a "jsonpCallback" manually on frontend and catch him on backend side
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'get_ip',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
In this case backend response seems like
get_ip({"ip":"192.168.1.1"})
add a comment |
In jsonp request you should catch "jsonpCallback" and send him back.
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
On backend side (if you use as backend PHP)
echo $_GET['callback'].'({"ip":"192.168.1.1"})';
In this case backend response seems like
jQuery331009526199802841284_1533646326884({"ip":"192.168.1.1"})
but you can set a "jsonpCallback" manually on frontend and catch him on backend side
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'get_ip',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
In this case backend response seems like
get_ip({"ip":"192.168.1.1"})
In jsonp request you should catch "jsonpCallback" and send him back.
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
On backend side (if you use as backend PHP)
echo $_GET['callback'].'({"ip":"192.168.1.1"})';
In this case backend response seems like
jQuery331009526199802841284_1533646326884({"ip":"192.168.1.1"})
but you can set a "jsonpCallback" manually on frontend and catch him on backend side
$.ajax({
url: lnk,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'get_ip',
success: function (ip) { console.log(ip.ip); },
error: function (err) { console.log(err) }
});
In this case backend response seems like
get_ip({"ip":"192.168.1.1"})
answered Aug 7 '18 at 13:38
Alexey KolotseyAlexey Kolotsey
462
462
add a comment |
add a comment |
in case you want to fix this on the backend (in Flask), rather than on the front end, I would totally recommend the Flask CORS python package. Flask Cors
With one simple line in your app.py you can automatically insert the standard allow any origin header, or customise it as required.
add a comment |
in case you want to fix this on the backend (in Flask), rather than on the front end, I would totally recommend the Flask CORS python package. Flask Cors
With one simple line in your app.py you can automatically insert the standard allow any origin header, or customise it as required.
add a comment |
in case you want to fix this on the backend (in Flask), rather than on the front end, I would totally recommend the Flask CORS python package. Flask Cors
With one simple line in your app.py you can automatically insert the standard allow any origin header, or customise it as required.
in case you want to fix this on the backend (in Flask), rather than on the front end, I would totally recommend the Flask CORS python package. Flask Cors
With one simple line in your app.py you can automatically insert the standard allow any origin header, or customise it as required.
answered Aug 11 '18 at 10:46
Ben WattsBen Watts
291
291
add a comment |
add a comment |
For Ruby on Rails server in application_controller.rb
, add this:
after_action :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
end
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
For Ruby on Rails server in application_controller.rb
, add this:
after_action :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
end
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
For Ruby on Rails server in application_controller.rb
, add this:
after_action :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
end
For Ruby on Rails server in application_controller.rb
, add this:
after_action :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
end
edited Sep 23 '17 at 23:40
Peter Mortensen
13.8k1987113
13.8k1987113
answered Aug 11 '17 at 7:39
张健健张健健
2,6861208
2,6861208
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
1
1
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
The question says "I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?". This is not an answer to the question that was asked.
– Quentin
Sep 13 '17 at 8:40
add a comment |
1 2
next
protected by Community♦ Apr 17 '15 at 16:02
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
23
Are you doing the request from localhost or direcly executing HTML?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:31
@MD.SahibBinMahboob If I understand your question I do request from localhost - I have page on my computer and just run it. When I deploy site on hosting it's gave same result.
– Mr Jedi
Nov 17 '13 at 19:43
is the domain of your executed page and requested domain name same or different?
– MD. Sahib Bin Mahboob
Nov 17 '13 at 19:47
4
much related: stackoverflow.com/questions/10143093/…
– cregox
Jul 7 '14 at 16:39
7
For anyone looking for more reading, MDN has a good article all about ajax and cross origin requests: developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
– Sam Eaton
Jun 18 '15 at 15:22