Javascript Access-Control-Allow-Origin 不允许 Origin

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10143093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:02:54  来源:igfitidea点击:

Origin is not allowed by Access-Control-Allow-Origin

javascriptajaxcorsxmlhttprequestcross-domain

提问by Ricardo

I'm making an Ajax.requestto a remote PHP server in a Sencha Touch2 application (wrapped in PhoneGap).

我正在Sencha Touch2 应用程序(包装在PhoneGap 中Ajax.request中创建一个远程 PHP 服务器。

The response from the server is the following:

来自服务器的响应如下:

XMLHttpRequest cannot load http://nqatalog.negroesquisso.pt/login.php. Origin http://localhost:8888is not allowed by Access-Control-Allow-Origin.

XMLHttpRequest 无法加载http://nqatalog.negroesquisso.pt/login.php。原产地http://localhost:8888不被访问控制允许来源允许的。

How can I fix this problem?

我该如何解决这个问题?

回答by Matt Mombrea

I wrote an article on this issue a while back, Cross Domain AJAX.

不久前我写了一篇关于这个问题的文章,跨域 AJAX

The easiest way to handle this if you have control of the responding server is to add a response header for:

如果您可以控制响应服务器,最简单的处理方法是为以下内容添加响应标头:

Access-Control-Allow-Origin: *

This will allow cross-domain Ajax. In PHP, you'll want to modify the response like so:

这将允许跨域Ajax。在 PHP 中,您需要像这样修改响应:

<?php header('Access-Control-Allow-Origin: *'); ?>

You can just put the Header set Access-Control-Allow-Origin *setting in the Apacheconfiguration or htaccess file.

您可以将Header set Access-Control-Allow-Origin *设置放在Apache配置或 htaccess 文件中。

It should be noted that this effectively disables CORS protection, which very likely exposes your users to attack. If you don't know that you specifically need to use a wildcard, you should not use it, and instead you should whitelist your specific domain:

应该注意的是,这有效地禁用了 CORS 保护,这很可能使您的用户受到攻击。如果您不知道您特别需要使用通配符,则不应使用它,而应将您的特定域列入白名单:

<?php header('Access-Control-Allow-Origin: http://example.com') ?>

回答by Travis Webb

If you don'thave control of the server, you can simply add this argument to your Chrome launcher: --disable-web-security.

如果你具备服务器的控制权,你可以这种说法只是添加到您的Chrome启动:--disable-web-security

Note that I wouldn't use this for normal "web surfing". For reference, see this post: Disable same origin policy in Chrome.

请注意,我不会将其用于正常的“网上冲浪”。如需参考,请参阅此帖子:在 Chrome 中禁用同源策略

One you use Phonegap to actually build the application and load it onto the device, this won't be an issue.

您使用 Phonegap 实际构建应用程序并将其加载到设备上,这不会成为问题。

回答by Reza S

If you're using Apache just add:

如果您使用的是 Apache,只需添加:

<ifModule mod_headers.c>
    Header set Access-Control-Allow-Origin: *
</ifModule>

in your configuration. This will cause all responses from your webserver to be accessible from any other site on the internet. If you intend to only allow services on your host to be used by a specific server you can replace the *with the URL of the originating server:

在您的配置中。这将导致您的网络服务器的所有响应都可以从互联网上的任何其他站点访问。如果您打算只允许特定服务器使用您主机上的服务,您可以将 替换*为原始服务器的 URL:

Header set Access-Control-Allow-Origin: http://my.origin.host

回答by C. Augusto Proiete

If you have an ASP.NET/ ASP.NET MVCapplication, you can include this header via the Web.config file:

如果您有ASP.NET/ ASP.NET MVC应用程序,则可以通过 Web.config 文件包含此标头:

<system.webServer>
  ...

    <httpProtocol>
        <customHeaders>
            <!-- Enable Cross Domain AJAX calls -->
            <remove name="Access-Control-Allow-Origin" />
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

回答by badMonkey

This was the first question/answer that popped up for me when trying to solve the same problem using ASP.NET MVCas the source of my data. I realize this doesn't solve the PHPquestion, but it is related enough to be valuable.

这是我尝试使用ASP.NET MVC作为数据源解决相同问题时出现的第一个问题/答案。我意识到这并不能解决PHP问题,但它足够有价值。

I am using ASP.NET MVC. The blog post from Greg Brantworked for me. Ultimately, you create an attribute, [HttpHeaderAttribute("Access-Control-Allow-Origin", "*")], that you are able to add to controller actions.

我正在使用 ASP.NET MVC。Greg Brant博文对我有用。最终,您创建了一个属性,[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")],您可以将其添加到控制器操作中。

For example:

例如:

public class HttpHeaderAttribute : ActionFilterAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }
    public HttpHeaderAttribute(string name, string value)
    {
        Name = name;
        Value = value;
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.AppendHeader(Name, Value);
        base.OnResultExecuted(filterContext);
    }
}

And then using it with:

然后将其用于:

[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
public ActionResult MyVeryAvailableAction(string id)
{
    return Json( "Some public result" );
}

回答by steve0hh

As Matt Mombrea is correct for the server side, you might run into another problem which is whitelisting rejection.

由于 Matt Mombrea 对于服务器端是正确的,您可能会遇到另一个问题,即拒绝白名单。

You have to configure your phonegap.plist. (I am using a old version of phonegap)

你必须配置你的 phonegap.plist。(我使用的是旧版本的phonegap)

For cordova, there might be some changes in the naming and directory. But the steps should be mostly the same.

对于cordova,命名和目录可能会有一些变化。但是步骤应该大致相同。

First select Supporting files > PhoneGap.plist

首先选择 Supporting files > PhoneGap.plist

enter image description here

在此处输入图片说明

then under "ExternalHosts"

然后在“外部主机”下

Add a entry, with a value of perhaps "http://nqatalog.negroesquisso.pt" I am using * for debugging purposes only.

添加一个条目,其值可能为“ http://nqatalog.negroesquisso.pt” 我使用 * 仅用于调试目的。

enter image description here

在此处输入图片说明

回答by lewsid

This might be handy for anyone who needs to an exception for both 'www' and 'non-www' versions of a referrer:

这对于需要“www”和“非 www”版本的引荐来源网址例外的人来说可能很方便:

 $referrer = $_SERVER['HTTP_REFERER'];
 $parts = parse_url($referrer);
 $domain = $parts['host'];

 if($domain == 'google.com')
 {
         header('Access-Control-Allow-Origin: http://google.com');
 }
 else if($domain == 'www.google.com')
 {
         header('Access-Control-Allow-Origin: http://www.google.com');
 }

回答by Francis Baptiste

I've run into this a few times when working with various APIs. Often a quick fix is to add "&callback=?" to the end of a string. Sometimes the ampersand has to be a character code, and sometimes a "?": "?callback=?" (see Forecast.io API Usage with jQuery)

我在使用各种 API 时遇到过几次这种情况。通常,快速解决方法是添加“&callback=?” 到字符串的末尾。有时&符号必须是字符代码,有时是“?”:“?callback =?” (请参阅Forecast.io API 与 jQuery 的使用

回答by Dibish

I will give you a simple solution for this one. In my case I don't have access to a server. In that case you can change the security policy in your Google Chromebrowser to allow Access-Control-Allow-Origin. This is very simple:

我会给你一个简单的解决方案。就我而言,我无权访问服务器。在这种情况下,您可以更改Google Chrome浏览器中的安全策略以允许 Access-Control-Allow-Origin。这很简单:

  1. Create a Chrome browser shortcut
  2. Right click short cut icon -> Properties -> Shortcut -> Target
  1. 创建 Chrome 浏览器快捷方式
  2. 右键单击快捷方式图标 -> 属性 -> 快捷方式 -> 目标

Simple paste in "C:\Program Files\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security.

简单粘贴"C:\Program Files\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security

The location may differ. Now open Chrome by clicking on that shortcut.

位置可能不同。现在通过单击该快捷方式打开 Chrome。

回答by itzg

If you're writing a Chrome Extension and get this error, then be sure you have added the API's base URL to your manifest.json's permissions block, example:

如果您正在编写 Chrome 扩展程序并收到此错误,请确保已将 API 的基本 URL 添加到您manifest.json权限块中,例如:

"permissions": [
    "https://itunes.apple.com/"
]