简体   繁体   中英

AngularJS CORS issue in Chrome - No 'Access-Control-Allow-Origin' header is present on the requested resource

I'm doing a little exercise to familiarise myself with AngularJS and I have my app running on http://127.0.0.1:9000/ after I execute the necessary grunt task. Now I wish to write/teach myself how to allow a Authorization/Authentication request (basically a login form). I have a seperate project that has a REST API, this is running on http://127.0.0.1:3000/ - notice the difference in port numbers. The exercise is hosted on my local machine so I wish to use CORS for my requests as browser restrictions aren't an issue and the app is for my own amusement. In my angularJS app I have included the following code in my config to allow CORS requests:

// set up CORS...
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

In my Rest API / Node Project I include the CORS middleware available from https://www.npmjs.org/package/cors and I have enabled CORS for all requests, I have included the library like so:

cors = require('cors')

and then...

app.use(cors()); // this is in my app.configure

When I test the API using the Websore REST tool the data I desire is retured however when trying to access this is my AngularJS app the Chrome JavaScript console gives me the following error:

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

Is there anything I have missed with setting up CORS for AngularJS? Thanks in advance.

Phew, I seem to have fixed in... In my app I needed to put the requirements in the following order:

app.use(cors());
app.use(app.router);

The app.use(cors()); must come before the app.use(app.router);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM