Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
994 views
in Technique[技术] by (71.8m points)

google app engine - CORS - Using AJAX to post on a Python (webapp2) web service

This is going to be long:

Ok so I'm developing a google calendar gadget which sends requests to a Python webapp2 REST api hosted on Google App Engine.

The problem comes when I try to POST something it doesn't allows me because of CORS. In Chromes' DevTools it says:

Method: OPTIONS.

Status: (failed) Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

Origin https://hq34i4geprnp5vci191ljfuhcoerscl4-a-calendar-opensocial.googleusercontent.com is not allowed by Access-Control-Allow-Origin. 

I'm aware that this is because of CORS. Here:

Ajax - 'Origin localhost is not allowed by Access-Control-Allow-Origin'

It says that I have to add

Access-Control-Allow-Origin: *

To the headers, but then again I'm new to ajax and I wonder if it's done this way:

    $.ajax({
        type: "POST",
        url: "https://myapp.appspot.com/service",
        contentType: "application/json; charset=utf-8",
        data: data,
        beforeSend: function (request)
        {
            request.setRequestHeader("Access-Control-Allow-Origin", "*");
        }
        success: function(data) {
              alert("AJAX done");
        }
    });

Adding this headers the output is different (which makes me wonder if the origin has been allowed, though I don't really know):

Method: OPTIONS.

Status: (failed) Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

XMLHttpRequest cannot load https://myapp.appspot.com/service. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers. 

I've even found this:

http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

Which lets me do GET requests, but I'd like to learn how to do them without this.

Also on my webserver I have this:

...
    class webService(webapp2.RequestHandler):
         options(self):
               self.response.write('options')

         post(self):
               self.response.write('post')

    application = webapp2.WSGIApplication([
        ('/', MainPage),
        ('/service', webService)
    ], debug=True)

I don't know if I must add something more to the webserver, nor I've found info saying that I have to. Also I think I'm near to achieve the CORS request but, I can't find THE Example that explains it all.

Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...