请求的资源错误上没有“ Access-Control-allow-Origin”标头

我正在尝试获取一个新闻网站的信息。我想我应该使用 google 的 feed API 把 feed 转换成 json。下面的 url 将以 json 格式从提要返回10篇文章。http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http://feeds.feedburner.com/mathrubhumi

我使用下面的代码来获取上面的 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) {
//.....
}
});

但它不工作,我得到了下面的错误

无法加载 XMLHttpRequest Http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http%3a%2f%2ffeeds.feedburner.com%2fmathrubhumi. 请求的标头上没有“访问控制-允许-起源”标头 因此,原产地「 http://localhost」是不允许存取的。

我该怎么补救?

504075 次浏览

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

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

127.0.0.1   localhost yourdomain.com

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

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

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.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

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

You can find a Chrome extension that 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.

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.

Please use @CrossOrigin on the backendside in 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.'

This solution is working for me 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

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.cs file.

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

Then all done.

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

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.

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

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

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

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

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

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

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

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

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.

well, another way is that use cors proxy, you just need to add https://cors-anywhere.herokuapp.com/ before your URL.so your URL will be like https://cors-anywhere.herokuapp.com/http://ajax.googleapis.com/ajax/services/feed/load.

The proxy server receives the http://ajax.googleapis.com/ajax/services/feed/load from the URL above. Then it makes the request to get that server’s response. And finally, the proxy applies the

Access-Control-Allow-Origin: *

to that original response.

This solution is great because it works in both development and production. In summary, you’re taking advantage of the fact that the same-origin policy is only implemented in browser-to-server communication. Which means it doesn’t have to be enforced in server-to-server communication!

you can read more about the solution here on Medium 3 Ways to Fix the CORS Error

Another way to resolve them is adding the below piece of code in the main application class which contains the '@SpringBootApplication' and restart the server if required. This worked for me.

    @Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin","Access-Control-Allow-Origin",
"Content-Type","Accept","Authorization","Origin,Accept","X-Requested-With",
"Access-Control-Request-Method","Access-Control-Request-Headers"));
corsConfiguration.setExposedHeaders(Arrays.asList("Origin","Content-Type","Accept","Authorization",
"Access-Control-Allow-Origin","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET","PUT","POST","DELETE","OPTIONS"));
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
        

}

If you use Express
please add routes after use cors

app.use(cors());
app.use('/posts', postRoutes);