Search code examples
javascriptjquerypython-3.xtornado

How to respond to a GET request in tornado?


Just started learning HTTP, trying to make a simple client-to-server request to work in tornado. Here is my javascript function trigged by a button click:

function funcOnClick(){
    $.ajax({
        url: "http://localhost:8889/madTest",
        type: "GET",
        success: function(result){alert('success')},
        error: function(error){console.log(error)}
    })
}

And here is my server:

import tornado.ioloop
import tornado.web
import json


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        print('got the GET request')
        self.write('abc')


def make_app():
    return tornado.web.Application([
        (r"/madTest", MainHandler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(8889)
    print('server started, listening to 8889 ...')
    tornado.ioloop.IOLoop.current().start()

On clicking the button, I see "got the GET request" printed, so the server must have gotten the request. However, I got this error on console:

enter image description here

Any suggestions? Thanks!


Solution

  • The error message occurs when your JS or HTML page is served from a different domain and you're trying to make an AJAX request to a different domain. This is called CORS. For security reasons, web browsers restrict cross-domain AJAX requests unless allowed by the server.

    To be able to make cross origin AJAX requests, you'll need to set a header called Access-Control-Allow-Origin in your handler's response.

    You can do this in the prepare method of your handler:

    class MainHandler(...):
        def prepare(self):
            self.set_header('Access-Control-Allow-Origin', '*')
            # the wildcard - '*' - allows CORS from any domain
            # you should probably change it to your frontend 
            # domain name if you wan to restrict CORS to a single domain.
            # see Mozilla docs for more info