Welcome!

AngularJS + GAE webapp2 + CORS

I've just struggeled with some CORS issue using AngularJS with a Grunt server and GAE as the backend.

My website lives on localhost:9000 and my backend server will return a JSON object when calling localhost:8080/json

The problem is the following. When calling

$http({method: 'GET', url: 'http://localhost:8080/json'})
.success(function(data, status, header, configs) {
// success code
}
.error(function(data, status, header, configs) {
// error code
}

the server response is empty. The problem is because of CORS. The follwing setup needs to be done to solve the issue:

My backend script looks as follws:

import webapp2
import json

class MainPage(webapp2.RequestHandler):
    def get(self):
        # the next line enables CORS on the backend side
    	self.response.headers['Access-Control-Allow-Origin'] = '*'
    	self.response.headers['Content-Type'] = 'application/json'
    	obj = {'Cool': 'Ya', 'Stupid': 'No'}
    	self.response.out.write(json.dumps(obj))

app = webapp2.WSGIApplication([
    ('/json', MainPage),
], debug=True)

And in your app.js you need to add the follwing:

angular.module('App', [])

.config(['$httpProvider', function($httpProvider) {
	$httpProvider.defaults.useXDomain = true;
   	delete $httpProvider.defaults.headers.common['X-Requested-With'];
}])

.controller(['AppCtrl'], function() {
	// Code
})

 

<< Zurück zur vorherigen Seite