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:
我正在尝试通过连接在Flask中构建的RESTful API来使用JavaScript进行授权。然而,当我提出请求时,我得到如下错误:
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.
XMLHttpRequest不能加载http://myApiUrl/login。在请求的资源上不存在“访问控制允许源”的标题。因此,原点“null”不允许访问。
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?
我知道API或远程资源必须设置header,但是为什么当我通过Chrome扩展邮差提出请求时,它会起作用呢?
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);
});
934
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.
如果我理解正确,那么您正在对一个不同的域进行XMLHttpRequest,而不是您的页面。所以浏览器会阻止它,因为它通常允许出于安全原因的请求。当您想要跨域请求时,您需要做一些不同的事情。关于如何实现这一点的教程是使用CORS。
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
当你使用邮差时,他们不受此政策限制。从跨源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.
常规web页面可以使用XMLHttpRequest对象从远程服务器发送和接收数据,但它们受到相同的同源策略的限制。扩展不那么有限。扩展可以与源之外的远程服务器进行通信,只要它首先请求跨源权限。
416
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.
这不是用于生产的补丁,或者当应用程序必须显示给客户端时,这只在UI和后端开发在不同的服务器上、在生产中实际上是在同一台服务器上时才有用。例如:在为任何应用程序开发UI时,如果需要在本地将其指向后端服务器,那么在这种情况下,这是一个完美的解决方案。对于生产修复,必须将CORS头文件添加到后端服务器,以允许跨源访问。
The easy way is to just add the extension in google chrome to allow access using CORS.
简单的方法是在谷歌chrome中添加扩展,允许使用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
在Windows中,将此命令粘贴到运行窗口中。
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.
这将打开一个新的chrome浏览器,允许访问没有“访问控制允许来源”的头请求。
300
If you can deal with JSON in return, then try using JSONP (note the P at the end) for speaking between domains:
如果您可以处理JSON作为回报,那么请尝试使用JSONP(在末尾注意到P),以便在域之间进行对话:
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ......
Learn more about working with JSONP here:
了解更多关于JSONP的工作:
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.
JSONP的出现——本质上是一个协商一致的跨站点脚本攻击——打开了强大的内容mashup的大门。许多知名网站提供JSONP服务,允许您通过预定义的API访问其内容。
177
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,这很简单。在PHP页面的开头添加以下脚本,处理请求:
<?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).
警告:这包含了PHP文件的安全问题,它可以被攻击者调用。您必须使用会话和cookie来进行身份验证,以防止您的文件/服务攻击此攻击。您的服务容易受到跨站请求伪造(CSRF)的影响。
If you are using Node-red you have to allow CROS in the node-red/settings.js
file by un-commenting the following lines:
如果你使用的是Node-red,你必须允许在Node-red /设置中使用CROS。js文件不评论以下几行:
// 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"
},
119
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.
我希望有人和我分享这个网站很久以前的http://cors。与建立和依靠我自己的代理相比,它将节省大量的时间。但是,当您开始生产时,拥有自己的代理是最好的选择,因为您仍然控制着数据的所有方面。
All you need:
你所需要的:
https://cors.io/?http://HTTP_YOUR_LINK_HERE
https://cors.io/?http:/ / HTTP_YOUR_LINK_HERE
58
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.
有一个使用Ajax的跨域问题。您必须确保在没有www的情况下访问相同的http://路径上的文件。(或者从http://www访问。并发布到相同的路径,包括www。)浏览器在访问www时将其视为另一个域。路径,你可以看到问题在哪里。您将发布到一个不同的域,浏览器会阻塞流,因为源问题。
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.
如果API没有放置在您请求的相同主机上,那么流将被阻塞,您将需要找到另一种方法来与API通信。
48
If you are using Node.js, try it:
如果您正在使用节点。js,试一试:
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
更多信息:关于ExpressJS的CORS。
38
Because
$.ajax({type: "POST" - Calls OPTIONS
$.post( - Calls POST
因为美元。ajax({类型:“POST”-调用选项$)。(——调用post
both are different Postman calls "POST" properly but when we call it will be "OPTIONS"
两者都是不同的邮递员,但当我们称它为“选项”时
For c# web services - webapi
对于c# web服务—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
请确保您在ajax调用中没有做任何错误。
jQuery
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/
角度4的问题请参考:http://www.hubfly.com/blog/solutions/howto -fix- Angular -4-api-call-issue /。
Note: If you are looking downloading content from third party website then this will not help you. You can try the following code but not JavaScript.
注意:如果你从第三方网站下载内容,这对你没有帮助。您可以尝试以下代码,但不是JavaScript。
System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");
22
Try XDomain,
尝试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.
概要:纯JavaScript CORS替代/polyfill。不需要服务器配置——只需添加一个代理。在您希望与之通信的域上的html。这个库使用XHook来钩住所有XHR,所以XDomain应该与任何库一起工作。
9
If you do NOT want to:
如果你不想:
and you are sure that your server has CORS enabled then (test CORS here: http://www.test-cors.org/)
并且您确定您的服务器已经启用了CORS(在这里测试CORS: 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.wikibackpacker.com/app/detail/Campgrounds/3591
你可以在这里看到它的作用:http://www.wikibackpacker.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.
编辑功能向不同的域发送GET & POST请求,以获取数据。我设置了原点参数来解决这个问题。后端是mediaWiki引擎。
tldr: Add "origin" parameter to your calls which must be the Origin parameter that your browser sends (you cannot spoof the origin parameter)
将“origin”参数添加到您的调用中,您的调用必须是您的浏览器发送的原始参数(您不能对原始参数进行修改)
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.
当我使用AngularJS访问我的API时,我遇到了一个问题。在SoapUI 5.0和ColdFusion中也有同样的请求。我的GET方法已经有了accesscontrol - control - allow- origin头。
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.
我发现AngularJS提供了一个“试用”选项请求。默认情况下,ColdFusion会生成选项方法,但它没有太多,这些header是具体的。错误是在对该选项调用的响应中生成的,而不是我的故意调用。在我的API添加了OPTIONS方法之后,问题就解决了。
<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>
8
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
服务器端:SparkJava——>提供了REST-API客户端:ExtJs6——>提供了浏览器呈现。
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")}
});
8
Based on shruti's answer, I've created a shortcut of Chrome browser with needed arguments:
基于shruti的回答,我创建了一个Chrome浏览器的快捷方式,需要参数:
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:
您可以通过使用YQL来通过Yahoo服务器代理请求来绕过这个问题。这只是几行代码:
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
这里有一个与解释相关的链接:https://vverma.net/fetchany-jsonp -jsonp- yql.html。
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.
如果您使用的是实体框架,那么即使启用了CORS,这个错误有时也会被抛出。我发现这个错误是由于查询的最后定稿而发生的。我希望这能在同样的情况下帮助别人。
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:
以下代码可以抛出XMLHttpRequest无法加载http://myApiUrl/login。在请求的资源上不存在“访问控制允许源”的标题。错误:
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:
要修复它,需要在查询结束时使用.ToList()或.FirstOrDefault()的finalization调用,如下所示:
using (DBContext db = new DBContext())
{
return db.Customers.Select(x => new
{
Name = x.Name,
CustomerId = x.CustomerId,
}).ToList();
}
5
In my case I was using JEE7 JAX-RS application and following tricks worked perfectly for me:
在我的例子中,我使用JEE7 JAX-RS应用程序,并且下面的技巧非常适合我:
@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();
}
5
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://github.com/rob-w/cors-anywhere/提供(Node.js)代码,您可以使用它来设置和运行您自己的CORS代理。它积极地维护并提供了许多特性,以控制代理行为,而不仅仅是正确的访问控制-*响应头的基本发送。
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.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS详细说明了浏览器如何处理来自JavaScript的客户端web应用程序的跨源请求,以及您必须将请求发送到服务器的哪些头文件(如果可以的话)。
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.
如果您需要向一个站点发出请求并得到响应,而不返回访问控制允许源的响应头,那么浏览器总是会阻止您的客户端JavaScript代码直接对其产生的跨源请求。因此,如果站点不是一个您可以控制并可以配置行为的站点,那么在这种情况下唯一能起作用的就是代理请求——通过您自己的代理运行您自己或者通过一个开放代理。
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.
正如在这里的其他评论中提到的,有充分的理由不相信一个开放的代理和您的请求。这就是说,如果你知道你在做什么,并且你决定一个开放的代理为你的需要工作,https://cors-anywhere.herokuapp.com/是一个可靠的,积极维护的,并且运行一个https://github.com/rob-w/cors-anywhere/代码的实例。
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.
这里提到的与其他开放代理(一对夫妇至少不似乎不再可用),它的工作方式是,而不是直接发送一个请求到您的客户端代码,例如,http://foo.com你将它发送给https://cors-anywhere.herokuapp.com/http:/ / foo.com和代理添加必要的访问控制- *头响应浏览器看到。
4
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.
我使用htaccess成功地解决了(在我的情况下是字体),但显然,OP的要求有点不同。但是您可以使用FileMatch模式并添加任何类型的扩展,这样它就不会产生cros错误。
<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
https://httpd.apache.org/docs/2.4/mod/core.html filesmatch
3
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.
很多时候,从javascript到php api都有这种情况,原因有几个。我忘了写
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.
这个错误的最后一个也是最重要的原因是,在您请求的页面上有一个解析错误。如果您在浏览器中点击这个页面url,您可能会看到一个解析错误,您将有一个行号来处理这个问题。
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.
我希望这能帮助别人。每次调试都花了我一段时间,我希望我有一个检查清单。
3
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.
这是一个很受欢迎的问题,如果你读了这么多,没有其他的帮助。如果您有一个CDN,如Akamai、焦点或类似的,您可能想要检查您对资源的URI所拥有的缓存键。如果它不包含源消息头值,那么您可能会在从另一个源请求时返回响应缓存。我们花了半天时间调试这个。CDN配置被更新为只包含一些选择域的原点值,并将其设置为null。这似乎是可行的,并且允许我们已知域的浏览器查看我们的资源。当然,所有其他的答案都是到达这里的先决条件,但是如果CDN是第一个从你的浏览器跳来的,这是值得回顾的。
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.
在我们的例子中,我们可以看到一些请求,使它能够服务于我们的服务,但并不是站点发送的数量。这指向了CDN。我们能够返回并看到原始请求是由直接请求提供的,而不是浏览器AJAX调用的一部分,也不包括响应头访问控制允许来源。显然,CDN缓存了这个值。Akamai CDN配置调整以考虑源请求头值作为匹配的一部分,似乎使它为我们工作。
3
For the GoLang API:
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.
首先,你可以看看MDN CORS Doc了解CORS是什么。据我所知,CORS是关于是否允许请求的来源访问服务器资源。
And you can restrict which request origin can access the server by setting Access-Control-Allow-Origin
at Header
of Server Response.
您可以通过在服务器响应的头设置访问控制- allow- origin来限制哪个请求源可以访问服务器。
For example, Setting following header in Server Response means that only request sent from http://foo.example
can access your server:
例如,在服务器响应中设置跟踪头意味着只从http://foo发送请求。示例可以访问您的服务器:
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.
在请求的资源上不存在“访问控制允许源”的标题。因此,原点“null”不允许访问。
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:
在GoLang中,我使用gorilla/mux包在本地主机上构建API服务器:9091,并且通过添加“访问控制-允许-来源”,“*”到响应头,允许CORS:
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
.
而且我在客户端使用JavaScript,在localhost:9092请求通过Chrome可以成功地从服务器localhost:9091获得“OKOK”。
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
.
此外,您还可以通过像Fiddler这样的工具检查请求/响应头。
2
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.
CORS是“跨源资源共享”,是发送跨域请求的一种方式。现在XMLHttpRequest2和Fetch API都支持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 '*').
如果您想要任何起源可以发送请求给您,您需要JSONP(也需要设置访问控制允许的来源,但是可以是'*')。
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
如果你不知道该选择什么,我认为你需要一个完整的功能部件来做这个。让我介绍一个简单的组件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.
如果您使用的是现代浏览器(> Internet Explorer9、Chrome、Firefox、Edge等),建议您使用一个简单但漂亮的组件,https://github.com/Joker-Jelly/catta。它没有依赖项,小于3kb,它支持Fetch、Ajax和JSONP,具有相同的死简单语法和选项。
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.
它还支持导入到您的项目的所有方法,比如ES6模块、CommonJS,甚至在HTML中
2
Most of these answers tell users how to add CORS headers to a server they control.
大多数答案告诉用户如何将CORS头添加到他们所控制的服务器上。
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:
但是,如果您需要从服务器中获得的数据,而不是在页面中进行控制,那么一个解决方案是在您的页面上创建一个脚本标记,将src属性设置为没有CORS头的api端点,然后将这些数据加载到页面上:
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);
1
I got this error with $http.get
in Angular. I needed to use $http.jsonp
instead.
我用$http得到这个错误。角。我需要使用$http。jsonp代替。
1
For Ruby on Rails server in application_controller.rb
, add this:
对于application_controller中的Ruby on Rails服务器。rb,添加:
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
0
For Opera (it works the same as Chrome), I started the browser with this command:
对于Opera(它的工作原理和Chrome一样),我用这个命令启动了浏览器:
opera --user-data-dir="~/Downloads/opera-session" --disable-web-security
The problem is solved! Now I can work on a local HTML file (on my hard disk drive) and call Ajax requests to remote origins in the same file.
问题已经解决了!现在,我可以在本地的HTML文件(在我的硬盘驱动器上)工作,并将Ajax请求调用到同一个文件中的远程数据源。
Note 1: You can give any folder in your home directory as --user-data-dir.
注1:您可以在您的主目录中提供任何文件夹—user-data-dir。
Note 2: Tested on Debian 8 (Jessie)/Opera 39
注2:测试Debian 8 (Jessie)/Opera 39。
When you start normally (without the parameters above), the same request falls into the error code block.
当您正常启动时(没有上面的参数),相同的请求就会落入错误代码块中。
0
Just to mention another way of "bypassing" it - AJAX proxy. Send request to your server to fetch the data from another origin and send the request back to you.
只是提到另一种“绕过”it - AJAX代理的方法。将请求发送到服务器,以从另一个源获取数据,并将请求发回给您。
I prefer this approach over JSONP because it has some potential security issues.
比起JSONP,我更喜欢这种方法,因为它有一些潜在的安全问题。
0
On my website (based on .NET) I've just added this:
在我的网站上(基于。net)我刚刚添加了这个:
<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.
非常感谢这段视频。
0
I have resolved this by enabling CORS for the client URL accessing the web API, and it worked successfully.
我解决了这个问题,通过为客户端URL访问web API启用了CORS,并且成功地工作了。
For example:
例如:
[EnableCors(origins: "http://clientaccessingapi.com", headers: "*", methods: "*")]
0
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://sx.xyz.com' is therefore not allowed access.
在请求的资源上不存在“访问控制允许源”的标题。因此,“https://sx.xyz.com”是不允许访问的。
I had also faced a similar problem with Cross Domain Data Exchange in the Ajax response as error undefined. But the response in header was Status Code:200 OK
我也遇到过类似的问题,在Ajax响应中跨域数据交换作为未定义的错误。但是header中的响应是状态代码:200 OK。
Failed to load https://www.Domain.in/index.php?route=api/synchronization/checkapikey:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://sx.xyz.in' is therefore not allowed access.
The solution to get around it: In my case it was to call the function checkapikey() via Ajax to another domain and get the response with data to where the call has been made:
绕过它的解决方案:在我的情况下,它将通过Ajax调用函数checkapikey()到另一个域,并在调用的地方得到响应:
if (($this->request->server['REQUEST_METHOD'] == 'POST') && isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Credentials: true');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
$headers = getallheaders();
...
}
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/11/17/6677806868c52d76b435cf9a7f6f285e.html。