No 'Access-Control-Allow-Origin' header is present

2,076 views
Skip to first unread message

Bryan Kardisco

unread,
May 8, 2014, 2:20:59 PM5/8/14
to cherryp...@googlegroups.com
I currently have two web-servers.

The first is a JBOSS server that runs on port 8080.   http://10.X.XX.XXXX:8080

I additionally have a CherryPy Server running on Port 8099

I'm attempting to have a .jsp page on the jboss server make an AJAX POST request to the CherryPy server like so

        var insertObj = {
            poi_id : "12345",
            obv_id : ""
        };
        var url = "http://10.X.XX.XXXX:8099/test";
        $.ajax({
            url : url,
            type : "POST",
            dataType : "json",
            data : JSON.stringify(insertObj),
            success : function(data) {
                alert(data);
            }
        });

 
My CherryPy server looks like this

import os
import cherrypy
import json

class MetroViz(object):
    @cherrypy.expose
    def index(self):
        return "Hello World!"
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    @cherrypy.tools.json_in()
    def test(self):
        print 'set up the response headers'
        cherrypy.response.headers["Access-Control-Allow-Origin"] = "http://localhost"
        cherrypy.response.headers["Allow"] = "POST, GET"
        input_json = cherrypy.request.json
        print input_json
           
    
def CORS(): 
    cherrypy.response.headers["Access-Control-Allow-Origin"] = "*" 
    
if __name__ == '__main__':
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
    port = int(os.environ.get('PORT', 8099))
    cherrypy.config.update({'server.socket_host': '10.X.XX.XXXX',
                        'server.socket_port': port,
                        'tools.CORS.on': True,
                       })
    cherrypy.quickstart(MetroViz())
    

I can directly go to http://10.X.XX.XXXX:8099/  and the page shows up no problem.  In my server console I get the following
10.22.2.253 - - [08/May/2014:14:16:15] "GET / HTTP/1.1" 200 12 "" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"


This is what I'd expect.  However, when trying to run the jQuery call from :8080 I get the following

XMLHttpRequest cannot load http://10.XX.X.XXXX:8099/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://10.XX.X.XXX:8080' is therefore not allowed access.

Additionally, when looking at my server console I'm told

10.22.2.253 - - [08/May/2014:14:17:39] "POST /test HTTP/1.1" 415 1343 "http://10.22.2.253:8080/METRO/sandbox/cherryPy.jsp" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"



Joel Rivera

unread,
May 8, 2014, 6:24:44 PM5/8/14
to cherryp...@googlegroups.com
On Thu, 8 May 2014 11:20:59 -0700 (PDT)
Bryan Kardisco <bryan.k...@gmail.com> wrote:

> cherrypy.config.update({'server.socket_host': '10.X.XX.XXXX',
> > 'server.socket_port': port,
> > 'tools.CORS.on': True,
> > })
> > cherrypy.quickstart(MetroViz())

How about changing this lines to this:


config = {'global': {
'server.socket_host':'10.X.XX.XXXX',
'server.socket_port': port
},
'/': {
'tools.CORS.on': True
}
}
cherrypy.quickstart(MetroViz, config=config)

I think that you need to enable the tool at the '/' or 'default' but
not in global, and thats what you are doing with the config.update.

You can also enable the tool with:

class MetroViz(object):
_cp_config = {'tools.CORS.on': True}
...

Cheers.
--
Rivera²

Joel Rivera

unread,
May 8, 2014, 6:28:46 PM5/8/14
to cherryp...@googlegroups.com
On Thu, 8 May 2014 17:24:44 -0500
Joel Rivera <riv...@joel.mx> wrote:

By this:

> cherrypy.quickstart(MetroViz, config=config)

I mean this:

cherrypy.quickstart(MetroViz(), config=config)

:)
--
Rivera²

Bryan Kardisco

unread,
May 9, 2014, 10:01:16 AM5/9/14
to cherryp...@googlegroups.com
Making the changes you've suggested - my code now looks like follow.

import os
import cherrypy
import json
import simplejson

class MetroViz(object):
    @cherrypy.expose
    def index(self):
        return "Hello World!"
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    @cherrypy.tools.json_in()
    def test(self):
        print 'set up the response headers'
        input_json = cherrypy.request.json
        result = {"operation": "request", "result": "success"}
        input_json = cherrypy.request.json
        # value = input_json["my_key"]
        return result
    
    def createJSON(self, title, d, pretty,):
        if d == [] or d == {}:
            return "{}"
        if pretty:
            return "<pre>" + json.dumps({title:d}, sort_keys=True, indent=4, separators=(',', ': ')) + "</pre>"
        return json.dumps({title:d}, sort_keys=True, indent=0, separators=(',', ':'))
    
  
def CORS():
    # Access-Control-Allow-Origin

    cherrypy.response.headers["Allow"] = "POST, GET"
    cherrypy.response.headers["Access-Control-Request-Headers"] = "x-requested-with"    
    cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
    cherrypy.response.headers["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept"
    cherrypy.response.headers["Content-Type"] = "application/json"
    print cherrypy.response.headers

    
if __name__ == '__main__':
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
    port = int(os.environ.get('PORT', 8099))
    config = {'global': { 
            'server.socket_host':'10.22.2.253',

             'server.socket_port': port 
           },
         '/': { 
              'tools.CORS.on': True 
          } 
      } 
    cherrypy.quickstart(MetroViz(), config=config) 
    
    cherrypy.quickstart(PyCachedAdmin(),
        config={
        '/': {
              'request.dispatch':
              cherrypy.dispatch.MethodDispatcher(),
    }})
    

And attempting to run this AJAX query results in the error: XMLHttpRequest cannot load http://10.22.2.253:8099/test. Invalid HTTP status code 500

The AJAX looks like this:

        $.support.cors = true;

        var insertObj = {
            poi_id : "12345",
            obv_id : ""
        };
        var myObject = {
            "my_key" : "my_value"
        };
        $.ajax({
            type : "POST",
            url : "http://10.22.2.253:8099/test",
            data : JSON.stringify(myObject),
            contentType : 'application/json',
            crossDomain: true,
            dataType : 'json',
            error : function() {
                alert("error");
            },
            success : function() {
                alert("success");
            }
        });

Bryan Kardisco

unread,
May 9, 2014, 11:00:43 AM5/9/14
to cherryp...@googlegroups.com
This is my whole error log output from CherryPy

[09/May/2014:10:57:25] HTTP 
Request Headers:
  ACCESS-CONTROL-REQUEST-HEADERS: accept, content-type
  REFERER: http://10.22.2.253:8080/METRO/sandbox/cherryPy.jsp
  HOST: 10.22.2.253:8099
  ORIGIN: http://10.22.2.253:8080
  CONNECTION: keep-alive
  Remote-Addr: 10.22.2.253
  ACCEPT: */*
  USER-AGENT: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
  ACCESS-CONTROL-REQUEST-METHOD: POST
  ACCEPT-LANGUAGE: en-US,en;q=0.8
  ACCEPT-ENCODING: gzip,deflate,sdch
[09/May/2014:10:57:25] HTTP Traceback (most recent call last):
  File "C:\Anaconda\lib\site-packages\cherrypy\_cprequest.py", line 656, in respond
    response.body = self.handler()
  File "C:\Anaconda\lib\site-packages\cherrypy\lib\encoding.py", line 188, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "C:\Anaconda\lib\site-packages\cherrypy\lib\jsontools.py", line 61, in json_handler
    value = cherrypy.serving.request._json_inner_handler(*args, **kwargs)
  File "C:\Anaconda\lib\site-packages\cherrypy\_cpdispatch.py", line 34, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "C:\Users\s362270.DVADLBE00335300\git\METROPython\METRO\com\ngc\metro\server\server.py", line 16, in test
    json = cherrypy.request.json
  File "C:\Anaconda\lib\site-packages\cherrypy\__init__.py", line 208, in __getattr__
    return getattr(child, name)
AttributeError: 'Request' object has no attribute 'json'
{'Access-Control-Request-Headers': 'x-requested-with', 'Server': 'CherryPy/3.2.3', 'Allow': 'POST, GET', 'Date': 'Fri, 09 May 2014 14:57:25 GMT', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept', 'Content-Type': 'application/json'}
Inside TEST
10.22.2.253 - - [09/May/2014:10:57:25] "OPTIONS /test HTTP/1.1" 500 1718 "http://10.22.2.253:8080/METRO/sandbox/cherryPy.jsp" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"
 

Eric Larson

unread,
May 9, 2014, 12:50:38 PM5/9/14
to cherryp...@googlegroups.com

Bryan Kardisco <bryan.k...@gmail.com> writes:

>> AttributeError: 'Request' object has no attribute 'json'

This error means the json_in tool is probably not working as
expected.

For debugging purposes, it might be worthwhile to remove the json_in/out
tools and do the parsing manually to make sure your CORS tool is working
as expected. Then you can reintroduce the json_in/out tools to see the
best way they should be applied.

HTH,

Eric

--
Sent with my mu4e

Bryan Kardisco

unread,
May 9, 2014, 1:01:38 PM5/9/14
to cherryp...@googlegroups.com
I thought that might be the issue so I tried the following:

        
        cl = cherrypy.request.headers['Content-Length']
        rawbody = cherrypy.request.body.read(int(cl))
        body = simplejson.loads(rawbody)
        print body

I get the following

[09/May/2014:12:58:30] HTTP 

Request Headers:
  ACCESS-CONTROL-REQUEST-HEADERS: accept, content-type
  REFERER: http://localhost:8080/METRO/sandbox/cherryPy.jsp
  HOST: localhost:8099
  ORIGIN: http://localhost:8080
  CONNECTION: keep-alive
  CACHE-CONTROL: max-age=0
  Remote-Addr: 127.0.0.1

  ACCEPT: */*
  USER-AGENT: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
  ACCESS-CONTROL-REQUEST-METHOD: POST
  ACCEPT-LANGUAGE: en-US,en;q=0.8
  ACCEPT-ENCODING: gzip,deflate,sdch
[09/May/2014:12:58:30] HTTP Traceback (most recent call last):

  File "C:\Anaconda\lib\site-packages\cherrypy\_cprequest.py", line 656, in respond
    response.body = self.handler()
  File "C:\Anaconda\lib\site-packages\cherrypy\lib\encoding.py", line 188, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "C:\Anaconda\lib\site-packages\cherrypy\lib\jsontools.py", line 61, in json_handler
    value = cherrypy.serving.request._json_inner_handler(*args, **kwargs)
  File "C:\Anaconda\lib\site-packages\cherrypy\_cpdispatch.py", line 34, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "C:\Users\s362270.DVADLBE00335300\git\METROPython\METRO\com\ngc\metro\server\server.py", line 32, in test
    cl = cherrypy.request.headers['Content-Length']
  File "C:\Anaconda\lib\site-packages\cherrypy\lib\httputil.py", line 359, in __getitem__
    return dict.__getitem__(self, str(key).title())
KeyError: 'Content-Length'
{'Access-Control-Request-Headers': 'x-requested-with', 'Server': 'CherryPy/3.2.3', 'Allow': 'POST, GET', 'Date': 'Fri, 09 May 2014 16:58:30 GMT', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept', 'Content-Type': 'application/json'}

set up the response headers
127.0.0.1 - - [09/May/2014:12:58:30] "OPTIONS /test HTTP/1.1" 500 1731 "http://localhost:8080/METRO/sandbox/cherryPy.jsp" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"

Eric Larson

unread,
May 9, 2014, 3:03:51 PM5/9/14
to cherryp...@googlegroups.com

Bryan Kardisco <bryan.k...@gmail.com> writes:

> I thought that might be the issue so I tried the following:
>
>
>
>> cl = cherrypy.request.headers['Content-Length']
>> rawbody = cherrypy.request.body.read(int(cl))
>> body = simplejson.loads(rawbody)
>> print body
>
>

Hmm. What about doing:

body = simplejson.load(cherrypy.request.body)
print body

I don't think the server absolutely requires a content-length header in
this case.

Also, if you want to hop on #cherrypy on irc.oftc.net, someone might be
able to help these smaller debug steps.

Eric

Bryan Kardisco

unread,
May 9, 2014, 3:08:10 PM5/9/14
to cherryp...@googlegroups.com
Thanks!  I'll have to hop on IRC tonight or this weekend.




--
You received this message because you are subscribed to a topic in the Google Groups "cherrypy-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/cherrypy-users/e0Qh6soKJnc/unsubscribe.
To unsubscribe from this group and all its topics, send an email to cherrypy-user...@googlegroups.com.
To post to this group, send email to cherryp...@googlegroups.com.
Visit this group at http://groups.google.com/group/cherrypy-users.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages