Javascript 请求的资源错误中不存在“Access-Control-Allow-Origin”标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28547288/
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-23 01:58:19  来源:igfitidea点击:

No 'Access-Control-Allow-Origin' header is present on the requested resource error

javascriptjqueryjsonajaxcors

提问by Aneeez

I'm trying to fetch the feed of a news website. Thought I'd use google's feed API to convert the feedburner feed into json. The following url will return 10 posts from the feed, in json format. http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http://feeds.feedburner.com/mathrubhumi

我正在尝试获取新闻网站的提要。以为我会使用谷歌的提要 API 将提要燃烧器提要转换为 json。以下 url 将从提要中以 json 格式返回 10 个帖子。http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http://feeds.feedburner.com/mathrubhumi

I used the following code to get the contents of above url

我使用以下代码来获取上述网址的内容

$.ajax({
  type: "GET",
  dataType: "jsonp",
  url: "http://ajax.googleapis.com/ajax/services/feed/load",
  data: {
    "v": "1.0",
    "num": "10",
    "q": "http://feeds.feedburner.com/mathrubhumi"
  },
  success: function(result) {
    //.....
  }
});

but it's not working and I'm getting the following error

但它不起作用,我收到以下错误

XMLHttpRequest cannot load http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http%3A%2F%2Ffeeds.feedburner.com%2Fmathrubhumi. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

XMLHttpRequest 无法加载 http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http%3A%2F%2Ffeeds.feedburner.com%2Fmathrubhumi。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost'。

How do I fix this?

我该如何解决?

采纳答案by thanix

I believe this might likely be that Chrome does not support localhostto go through the Access-Control-Allow-Origin-- see Chrome issue

我相信这可能是 Chrome 不支持localhost通过Access-Control-Allow-Origin--参见 Chrome 问题

To have Chrome send Access-Control-Allow-Originin the header, just alias your localhost in your /etc/hosts file to some other domain, like:

要让 Chrome 发送Access-Control-Allow-Origin标头,只需将 /etc/hosts 文件中的 localhost 别名为其他域,例如:

127.0.0.1   localhost yourdomain.com

Then if you'd access your script using yourdomain.cominstead of localhost, the call should succeed.

然后,如果您使用yourdomain.com而不是访问您的脚本localhost,则调用应该会成功。

回答by dkruchok

If you use Google Chrome browser you can hack with an extension.

如果您使用 Google Chrome 浏览器,则可以使用扩展程序进行破解。

You can find a Chrome extensionthat will modify CORS headers on the fly in your application. Obviously, this is Chrome only, but I like that it works with zero changes anywhere at all.

您可以找到一个Chrome 扩展程序,它可以在您的应用程序中动态修改 CORS 标头。显然,这仅适用于 Chrome,但我喜欢它可以在任何地方进行零更改。

You can use it for debugging your app on a local machine (if everything works in production).

您可以使用它在本地机器上调试您的应用程序(如果一切正常)。

Notice: If URL becomes broken the extension name is Access-Control-Allow-Origin: *. I recommend you to disable this extension when you not working on your stuff, because, for example, youtube does not work with this extension.

注意:如果 URL 损坏,扩展名是Access-Control-Allow-Origin: *。我建议您在不处理内容时禁用此扩展程序,因为例如,youtube 不支持此扩展程序。

回答by Mackander Singh

Try this - set Ajax call by setting up the header as follows:

试试这个 - 通过如下设置标题来设置 Ajax 调用:

var uri = "http://localhost:50869/odata/mydatafeeds"
$.ajax({
    url: uri,
    beforeSend: function (request) {
        request.setRequestHeader("Authorization", "Negotiate");
    },
    async: true,
    success: function (data) {
        alert(JSON.stringify(data));
    },
    error: function (xhr, textStatus, errorMessage) {
        alert(errorMessage);
    }                
});

Then run your code by opening Chrome with the following command line:

然后通过使用以下命令行打开 Chrome 来运行您的代码:

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

回答by vancy-pants

Just FYI, I noticed this information from the jQuery documentation which I believe applies to this issue:

仅供参考,我从 jQuery 文档中注意到了这个信息,我认为它适用于这个问题:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.

由于浏览器安全限制,大多数“Ajax”请求都遵循同源策略;请求无法从不同的域、子域、端口或协议成功检索数据。

Changing the hosts file like @thanix didn't work for me, but the extension mentioned by @dkruchok did solve the problem.

像@thanix 这样更改主机文件对我不起作用,但是@dkruchok 提到的扩展名确实解决了问题。

回答by Om.

If its calling spring boot service. you can handle it using below code.

如果它调用 spring boot 服务。您可以使用以下代码处理它。

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
                    .allowedHeaders("*", "Access-Control-Allow-Headers", "origin", "Content-type", "accept", "x-requested-with", "x-requested-by") //What is this for?
                    .allowCredentials(true);
        }
    };
}

回答by Kamil Kie?czewski

For development you can use https://cors-anywhere.herokuapp.com, for production is better to set up your own proxy

对于开发,您可以使用https://cors-anywhere.herokuapp.com,对于生产,最好设置自己的代理

async function read() {
   let r= await (await fetch('https://cors-anywhere.herokuapp.com/http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http://feeds.feedburner.com/mathrubhumi')).json();
   console.log(r);
}

read();

回答by Serkan AKMAN

cors unblock works great for chrome 78 [COrs unb] [1] https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino

cors unblock 适用于 chrome 78 [COrs unb] [1] https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino

it's a plugin for google chrome called "cors unblock"

这是一个名为“cors unblock”的谷歌浏览器插件

Summary:No more CORS error by appending 'Access-Control-Allow-Origin: *' header to local and remote web requests when enabled

摘要:通过在启用时将“Access-Control-Allow-Origin: *”标头附加到本地和远程 Web 请求,不再出现 CORS 错误

This extension provides control over XMLHttpRequest and fetch methods by providing custom "access-control-allow-origin" and "access-control-allow-methods" headers to every requests that the browser receives. A user can toggle the extension on and off from the toolbar button. To modify how these headers are altered, use the right-click context menu items. You can customize what method are allowed. The default option is to allow 'GET', 'PUT', 'POST', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH' methods. You can also ask the extension not to overwrite these headers when the server already fills them.

此扩展通过为浏览器接收的每个请求提供自定义的“access-control-allow-origin”和“access-control-allow-methods”标头来控制 XMLHttpRequest 和 fetch 方法。用户可以从工具栏按钮打开和关闭扩展。要修改这些标题的更改方式,请使用右键单击上下文菜单项。您可以自定义允许使用的方法。默认选项是允许 'GET'、'PUT'、'POST'、'DELETE'、'HEAD'、'OPTIONS'、'PATCH' 方法。您还可以要求扩展程序在服务器已经填充这些标头时不要覆盖它们。

回答by Sabrina Ahmed Khan

Chrome doesn't allow you to integrate two different localhost,that's why we are getting this error. You just have to include Microsoft Visual Studio Web Api Core package from nuget manager.And add the two lines of code in WebApi project's in your WebApiConfig.csfile.

Chrome 不允许您集成两个不同的本地主机,这就是我们收到此错误的原因。您只需要从 nuget manager 中包含 Microsoft Visual Studio Web Api Core 包。并在您的WebApiConfig.cs文件中添加 WebApi 项目中的两行代码。

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Then all done.

然后一切都完成了。

回答by Eddy Joseph

Please use @CrossOriginon the backendsidein Spring boot controller (either class level or method level) as the solution for Chrome error 'No 'Access-Control-Allow-Origin'header is present on the requested resource.'

请使用@CrossOriginbackendside春季引导控制器(或者类级别或方法级)作为铬错误溶液'No 'Access-Control-Allow-Origin'头存在于所请求的资源“。

This solution is working for me 100% ...

这个解决方案对我有用 100% ...

Example : Class level

示例:班级

@CrossOrigin
@Controller
public class UploadController {

----- OR -------

- - - 或者 - - - -

Example : Method level

示例:方法级别

@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RequestMapping(value = "/loadAllCars")
    @ResponseBody
    public List<Car> loadAllCars() {


Ref: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework