为什么我的JavaScript在所请求的资源上出现“No‘Access-Control-Allow-Origin‘标头”错误,当Postman没有?

为什么我的JavaScript在所请求的资源上出现“No'Access-Control-Allow-Origin'标头”错误,当Postman没有?

[英]Why does my JavaScript get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not?

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。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许原点'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或远程资源必须设置标题,但为什么在我通过Chrome扩展程序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);    });

38 个解决方案

#1


1053  

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:

当您使用邮递员时,他们不受此政策的限制。引自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.

常规网页可以使用XMLHttpRequest对象从远程服务器发送和接收数据,但它们受到相同原始策略的限制。扩展不是那么有限。扩展可以与其来源之外的远程服务器通信,只要它首先请求跨源权限即可。

#2


464  

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.

简单的方法是在谷歌浏览器中添加扩展名以允许使用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.

只要您希望不允许访问“access-control-allow-origin”标头请求,只需启用此扩展。

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浏览器,允许访问没有'access-control-allow-origin'标头请求。

#3


317  

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的出现 - 本质上是一个双方同意的跨站点脚本黑客 - 为强大的内容混搭打开了大门。许多着名网站都提供JSONP服务,允许您通过预定义的API访问其内容。

#4


192  

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 CORS in the node-red/settings.js file by un-commenting the following lines:

如果您使用的是Node-red,则必须通过取消注释以下行来允许node-red / settings.js文件中的CORS:

// 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


154  

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.io/与构建和依赖我自己的代理相比,它可以节省大量时间。但是,当您转向生产时,拥有自己的代理是最好的选择,因为您仍然可以控制数据的所有方面。

All you need:

一切你需要的:

https://cors.io/?http://HTTP_YOUR_LINK_HERE

#6


64  

If you are using Node.js, try it:

如果您使用的是Node.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

#7


62  

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通信的方式。

#8


44  

Because
$.ajax({type: "POST" - Calls OPTIONS
$.post( - Calls POST

因为$ .ajax({type:“POST” - 调用OPTIONS $ .post( - 调用POST

both are different Postman calls "POST" properly but when we call it will be "OPTIONS"

两者都是不同的Postman称之为“POST”,但当我们称之为“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

请在 标记下的web.config文件中添加以下代码。这会奏效

<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

$.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/

Angular 4问题请参考:http://www.hubfly.com/blog/solutions/how-to-fix-angular-4-api-call-issues/

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");

#9


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.

简介:纯JavaScript CORS替代/ polyfill。无需服务器配置 - 只需在要与之通信的域上添加proxy.html。该库使用XHook挂钩所有XHR,因此XDomain应该与任何库一起使用。

#10


9  

If you do NOT want to:

如果你不想:

在Chrome中停用网络安全

使用第三方网站重新路由您的请求

  1. Disable web security in Chrome
  2. Use JSONP
  3. 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/)

并且您确定您的服务器已启用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.

然后你需要在你的请求中传入origin参数。这个起源必须与你的浏览器发送的请求相匹配。

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请求发送到其他域以获取数据。我设置了解决问题的origin参数。后端是一个mediaWiki引擎。

tldr: Add "origin" parameter to your calls which must be the Origin parameter that your browser sends (you cannot spoof the origin parameter)

tldr:在调用中添加“origin”参数,该参数必须是浏览器发送的Origin参数(不能欺骗origin参数)

#11


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方法已经有了Access-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提出了“试用”OPTIONS请求。默认情况下,ColdFusion生成OPTIONS方法,但它没有太多,具体是这些标头。响应OPTIONS调用生成错误,而不是我故意调用GET。在我将API OPTIONS方法添加到我的API后,问题已得到解决。

<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>

#12


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")}});

#13


8  

Based on shruti's answer, I've created a shortcut of Chrome browser with needed arguments:

根据shruti的回答,我创建了一个Chrome浏览器的快捷方式,其中包含所需的参数:

#14


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/fetch-any-json-using-jsonp-and-yql.html

#15


6  

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代理。它主动维护并提供许多功能来控制代理行为,而不仅仅是基本发送正确的Access-Control- *响应头。

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详细介绍了浏览器如何处理客户端Web应用程序通过JavaScript进行的跨源请求以及您必须配置哪些标头的发送方式请求服务器,如果可以的话。

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.

如果您需要向其发出请求并获得响应的站点未返回Access-Control-Allow-Origin响应标头,则浏览器始终会阻止客户端直接向其发出的跨域请求工作的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/ 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.

与此处提到的其他开放代理(其中一些至少似乎不再可用)一样,它的工作方式是,而不是让您的客户端代码直接发送请求,例如,http:// foo您将其发送到https://cors-anywhere.herokuapp.com/http://foo.com,并且代理会将必要的Access-Control- *标头添加到浏览器看到的响应中。

#16


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.

如果您正在使用Entity Framework,即使您启用了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。请求的资源上不存在“Access-Control-Allow-Origin”标头。错误:

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(),如下所示:

using (DBContext db = new DBContext()){    return db.Customers.Select(x => new    {        Name = x.Name,        CustomerId = x.CustomerId,    }).ToList();}

#17


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();    }

#18


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模式并添加任何类型的扩展名,以便它不会产生交叉错误。

<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

#19


4  

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,Limelight或类似的CDN,您可能需要检查您拥有的资源URI的缓存密钥。如果它不包含Origin标头值,则可能在从另一个Origin请求时返回缓存的响应。我们花了半天时间调试这个。 CDN配置已更新为仅包含我们的几个选定域的Origin值,并为所有其他域设置为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调用的一部分,并且不包括响应头Access-Control-Allow-Origin。显然,CDN缓存了这个值。 Akamai CDN配置调整将原始请求标头值视为匹配的一部分似乎已使其适用于我们。

#20


4  

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是关于是否允许Origin Of Request访问Server Resource。

And you can restrict which request origin can access the server by setting Access-Control-Allow-Origin at Header of Server Response.

并且您可以通过在服务器响应的头部设置Access-Control-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.example发送的请求才能访问您的服务器:

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:

正如我在错误消息中所知,请求的资源意味着服务器的资源,因此请求的资源上不存在“Access-Control-Allow-Origin”标头。表示您没有在服务器响应中设置Access-Control-Allow-Origin标头,或者您可能已设置但请求的来源不是Access-Control-Allow-Origin中的列表,因此不允许请求访问:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许原点'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包在localhost:9091上构建API服务器,并通过向响应头添加“Access-Control-Allow-Origin”,“*”来允许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' routefunc 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可以成功从Server 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等工具检查您的请求/响应标头。

#21


4  

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:

当您尝试向无法控制的远程服务器执行Ajax POST / GET请求时,请忘记这个简单的修复:

<?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.

您真的需要,特别是如果您只使用JavaScript来执行Ajax请求,内部代理将接收您的查询并将其发送到远程服务器。

First in your JavaScript code, do an Ajax call to your own server, something like:

首先在您的JavaScript代码中,对您自己的服务器执行Ajax调用,例如:

$.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:

然后,创建一个名为proxy.php的简单PHP文件来包装POST数据,并将它们作为参数附加到远程URL服务器。我举例说明了如何使用Expedia Hotel搜索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复制并粘贴的答案

#22


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.

此错误的最后和最突出的原因是您请求的页面上存在解析错误。如果您在浏览器中点击该页面网址的可能性很大,您将看到解析错误,并且您将有一个行号来解决该问题。

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.

我希望这可以帮助别人。每次我花了一段时间来调试这个,我希望我有一份要核实的清单。

#23


2  

I got this error with $http.get in Angular. I needed to use $http.jsonp instead.

我在Angular中使用$ http.get得到了这个错误。我需要使用$ http.jsonp代替。

#24


2  

CORS is for you.

CORS适合你。

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 '*'.

但它有其局限性。服务器需要特定声明Access-Control-Allow-Origin,并且不能设置为'*'。

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(也需要设置Access-Control-Allow-Origin,但可以是'*')。

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。它没有依赖关系,小于3 KB,它支持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中的

#25


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);

#26


1  

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.

非常感谢这个视频。

#27


1  

For Ruby on Rails server in application_controller.rb, add this:

对于application_controller.rb中的Ruby on Rails服务器,添加以下内容:

after_action :cors_set_access_control_headersdef cors_set_access_control_headers  headers['Access-Control-Allow-Origin'] = '*'  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'  headers['Access-Control-Allow-Headers'] = '*'end

#28


1  

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://sx.xyz.com' is therefore not allowed access.

请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许来源“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响应中遇到了类似的跨域数据交换问题,因为错误未定义。但标题中的响应是状态码: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();...}

#29


1  

For completeness, Apache allows cors:

为了完整起见,Apache允许使用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"

#30


1  

Maybe is it a litte bit complicated but you can use a web server to route the request.With nodejs you havent this problem. I am not an expert in node js. So i dont know if this is clean code.

也许它有点复杂,但你可以使用Web服务器来路由请求。使用nodejs你没有这个问题。我不是节点js的专家。所以我不知道这是否是干净的代码。

But this works for me

但这对我有用

Here is a little exmaple:

这是一个小例子:

NODE JS

var rp = require('request-promise');var express = require('express'),    app = express(),    port = process.env.PORT || 3000;var options = {    method: 'POST',    uri: 'http://api.posttestserver.com/post',    body: {        some: 'payload'    },    json: true // Automatically stringifies the body to JSON};app.get('/', function (req, res) {        rp(options)        .then(function (parsedBody) {            res.send(parsedBody)        })        .catch(function (err) {            res.send(err)        });});app.listen(port);

JS

axios.get("http://localhost:3000/").then((res)=>{    console.log('================res====================');    console.log(res);    console.log('====================================');})

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值