1

I'm trying to make an API call to a third party service, with the following JS:

<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.something.com/apikeyetcetc", false);
xhr.send();

console.log(xhr.status);
</script>

However, at the xhr.send() line, it triggers this error in the browser's console:

XMLHttpRequest cannot load https://api.something.com/apikeyetcetc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access.

I'm running a local server using MAMP from www.mamp.info on a fresh install of macOS Sierra.

I created a .htaccess file in the same directory as the HTML file I've created, and added the following line:

Header set Access-Control-Allow-Origin "*"

But it doesn't seem to have helped. I see a lot of varying suggestions about CORS on Apache and other configurations, but I want to make sure I know what's going on here before randomly trying things (especially while I still have a clean dev environment). Any thoughts what might be going on?

Edit: The API I'm trying to use is Dark Sky.

chimerical
  • 5,883
  • 8
  • 31
  • 37
  • Some solutions here ~ http://stackoverflow.com/questions/15005500/loading-cross-domain-html-page-with-ajax – Phil Oct 14 '16 at 02:33
  • use cURL on your server to proxy the request – charlietfl Oct 14 '16 at 02:38
  • @Phil Wait, why is this being marked as a duplicate? It touches on similar areas, but the question in your thread was asking something different, and doesn't really have a single solution as opposed to a scatter of general links about same-origin policy and CORS? – chimerical Oct 14 '16 at 19:39
  • The answer lies in that Dark Sky (as mentioned in his edit) disables CORS entirely and recommends you use a proxy server of your own in order to prevent people from stealing your API key: https://darksky.net/dev/docs/faq#cross-origin – rpearce Jan 15 '17 at 12:49

1 Answers1

1

The issue that your having isn't because of settings on your local server, so adding an .htaccess file won't help.

The issue is because the response from the server hosting the API doesn't have the Access-Control-Allow-Origin header. May I ask what API it is that you're trying to use?

If the API is beyond your control you have a few options, you could set up a CORS proxy using NodeJS. There's a few of these e.g. https://www.npmjs.com/package/corsproxy

Alternatively, for while you're developing you could install a browser extension that prevents the browser from blocking the request. I know there are a few for Chrome, and I imagine Firefox would have at least one. (Just remember to disable it when you're not using it as it can cause issues with other websites).

DanDooley
  • 35
  • 7