112

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

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.

How do I fix this?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Aneeez
  • 1,422
  • 3
  • 15
  • 20
  • 1
    I tested your code here, with Chrome and worked as expected. Have you tried to use "crossDomain: true" attribute? – Daniel Loureiro Feb 16 '15 at 17:57
  • I hosted your code here: http://learnwithdaniel.com/test.html . see if you can open without errors. If you not get an error, the problem its with your server – Daniel Loureiro Feb 16 '15 at 18:01
  • great. So its related with the headers that you server send when your browser makes a request for this html. Check for "cors headers" – Daniel Loureiro Feb 16 '15 at 18:09
  • same here with godaddy api – Gilson Gilbert Dec 06 '16 at 09:21
  • Isn't this question a duplicate? http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource More importantly, this other question has clearer / more thorough answers. – Nate Anderson Mar 18 '17 at 00:03
  • Does this answer your question? [Disable same origin policy in Chrome](https://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome) – Michael Freidgeim May 08 '20 at 21:48

12 Answers12

114

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.

Community
  • 1
  • 1
dkruchok
  • 1,829
  • 3
  • 19
  • 25
  • This definitely worked for me too!...i think the developer of the plugin has updated it to fit certain urls you input manually than working for everything, I visited Youtube and other sites and it works just fine. Anyways thanks a lot. – Kingston Fortune May 13 '18 at 21:53
  • 1
    it is only for testing while development. The users are not going to add the plugin in browser – Abdulmoiz Ahmer Oct 18 '19 at 10:31
  • Looks like that extension is no longer available, at least at that URL. This extension seems to work, however: https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf – Gordon Nov 19 '19 at 00:07
  • 1
    But what is this extension _doing_? Do you know of an open-source version or what to do to write one that modifies headers this way? You probably don't want (well, okay, _I_ don't want) to run an extension that has full access to URLs and data without knowing what it's doing. Seems like that could be a _very_ bad idea if the extension changes hands, is already nefarious, etc. **EDIT:** [The one mentioned below](https://stackoverflow.com/revisions/59115490/2) is [open source](https://github.com/balvin-perrie/Access-Control-Allow-Origin---Unblock/), fwiw. – ruffin Apr 23 '20 at 18:25
  • @ruffin Thank you for pointing this one out! In addition, it's worth mentioning this opensource Chrome plugin CORS Unblock is also available on Firefox and Microsoft Edge. – gaborous Jan 01 '21 at 03:19
  • Literally using "localhost" instead of "127.0.0.1" in the browser, solved the CORS issue for me. – m_ocean Dec 17 '22 at 19:46
90

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.

Amirhossein Mehrvarzi
  • 18,024
  • 7
  • 45
  • 70
thanix
  • 1,287
  • 9
  • 5
  • Thank you. I was experiencing this issue and switching to IE edge, caused me to see the underlying error in my server code which was being obscured by Chrome's denial of localhost. – Aluan Haddad Dec 20 '15 at 21:53
  • 8
    Doesn't work for me either. Perhaps an update to Chrome blocked this "loophole"? – Marty C. Feb 29 '16 at 18:56
  • 3
    No help here either. My website is already set up this way, however I do have one big difference. I'm using a different port. I'm sure if it were the same port, it would work. HTTP vs. HTTPS are of course different ports, so that might cause some of you issues. Mine isn't HTTPS in particular, but I am trying to access something on the same domain but a different port other than 80. – Jerry Dodge Jul 16 '16 at 22:23
  • What if the API is being accessed by a chrome extensions, what can be done – viveksinghggits Jun 08 '18 at 19:52
10

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
Pang
  • 9,564
  • 146
  • 81
  • 122
Mackander Singh
  • 101
  • 1
  • 4
4

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"

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

Email
  • 2,395
  • 3
  • 35
  • 63
Serkan AKMAN
  • 1,044
  • 2
  • 8
  • 21
  • As noted by another commenter above, [this plugin is opensource](https://github.com/balvin-perrie/Access-Control-Allow-Origin---Unblock/), which is very nice considering this kind of plugin has access to all URLs, so transparency is appreciated. It is also available on Firefox and Microsoft Edge. Nice finding! Thank you for sharing! – gaborous Jan 01 '21 at 03:16
2

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);
        
    }
Keshav Pradeep Ramanath
  • 1,623
  • 4
  • 24
  • 33
1

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.

vancy-pants
  • 1,070
  • 12
  • 13
0

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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);
        }
    };
}
Om.
  • 2,532
  • 4
  • 22
  • 22
0

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();
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

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

Mo0rteza
  • 320
  • 6
  • 18
  • 1
    As of 31 Januaray 2021 cors-anywhere has been limited due to abuse and generally should not be used in production, unless your number of requests per day are very limited. https://github.com/Rob--W/cors-anywhere/issues/301 – Miqi180 Feb 21 '21 at 02:47
0

If you use Express
please add routes after use cors

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

-3

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
ThisaruG
  • 3,222
  • 7
  • 38
  • 60
Eddy Joseph
  • 147
  • 1
  • 1
  • 1
    While this certainly does not answer the question of OP, it has a valid point. Consuming Spring RESTful Services/Data through javascript does require you to set the `@CrossOrigin` Annotation. To all those who downvote: Please state your reason! – rwenz3l Jul 23 '18 at 07:50
  • While this answer is a bit off topic for this particular question, it certainly solved *my* problem. – ljleb Feb 03 '21 at 22:02