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?
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.
回答2:
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.
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.
回答4:
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:
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"
},
回答5:
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.
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.
回答8:
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
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");
share|improve this answer
edited Nov 13 '18 at 9:27
answered Dec 13 '16 at 13:02
George LivingstonGeorge Livingston
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 * use https://www.myotherdomain.com
– pechar
Jun 9 '17 at 8:30
add a comment |
22
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.
share|improve this answer
edited Jan 9 '15 at 19:19
ygormutti
143113
answered Apr 1 '14 at 7:46
user3359786user3359786
22122
add a comment |
11
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)
share|improve this answer
edited Jan 19 at 17:54
answered Jul 7 '16 at 4:26
Ganesh KrishnanGanesh Krishnan
4,44423040
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
@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 |
8
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.
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 |
8
I had the following configuration, resulting in the same error, when requesting responses from the server.
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")}
});
share|improve this answer
edited Jun 28 '16 at 3:46
Ani Menon
16k85876
answered Sep 18 '15 at 14:50
kiltekkiltek
1,69843558
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 |
8
Based on shruti's answer, I've created a shortcut of Chrome browser with needed arguments:
share|improve this answer
edited May 23 '17 at 11:47
Community♦
11
answered Jul 2 '16 at 23:52
Mohammad AlBannaMohammad AlBanna
1,2931117
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 |
7
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.
share|improve this answer
edited May 21 '17 at 10:39
Peter Mortensen
13.7k1986112
answered Mar 12 '17 at 7:01
sideshowbarkersideshowbarker
32.8k147896
add a comment |
7
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
share|improve this answer
edited May 21 '17 at 11:39
Peter Mortensen
13.7k1986112
answered Nov 21 '16 at 14:59
camnesiacamnesia
337311
but after seconds ... all the other codes run then it initialize.
– saber tabatabaee yazdi
Jun 8 '17 at 16:16
add a comment |
5
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();
}
*
usehttps://www.myotherdomain.com
– pechar Jun 9 '17 at 8:30