Tom V Tom V - 1 year ago 89
AngularJS Question

I am getting No 'Access-Control-Allow-Origin' header when trying to call an API

Edit: It may be worth noting that I am domain registered at GoDaddy which forwards with masking to my Bitnami IP. My stack is all on the same server, that's why I do not understand the cross site nature of this issue. Or maybe I am understanding it wrong. Please help me understand this error.

I know there are other threads similar to this, but I didn't see any matching my exact setup.

I have an Amazon AWS EC2 Bitnami MEAN stack running an AngularJS site. I am posting some info I gathered externally with some Python scripts into a mongodb and then I have a JS API that successfully posts the collection via port 3000 ... all pretty standard from what I can tell. I am just learning this technology and am pretty novice.

So When I go to the API [URL]:3000/api in Chrome I see the JSON results. This has not been a problem.

When my Angular site's controller tries to do a $http GET on the API URL, Express logs and displays in my putty console to Bitnami that I am indeed hitting the API.

BUT.. Chrome is giving me this sweet error on the page when I F12 debug:

XMLHttpRequest cannot load **URL**. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin **URL**' is therefore not allowed access.

Sorry for all the fake URLs, I'm newer to stackoverflow and it flagged me as using "more than 2 URLs" because I don't have 10 points.

Thank you so much in advance for helping me understand this problem.

Answer Source

The reason for this error is simple, you are making an API call to as separate domain from the one your angular app is being served from. Chrome or any other browser will normally throw a CORS error.

What you will have to do is to go to your API and whitelist the domain from which your angular app is running. I am not sure how it is done in python, but in NodeJS below is what I will do.

var cors = require('cors');
corsOptions = {
  origin: [
  credentials: true

For python this might help, not sure

From the documentation of CORS, to enable all CORS

var express = require('express')
  , cors = require('cors')
  , app = express();


app.get('/products/:id', function(req, res, next){
  res.json({msg: 'This is CORS-enabled for all origins!'});

app.listen(80, function(){
  console.log('CORS-enabled web server listening on port 80');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download