Bottle Py: Enabling CORS for jQuery AJAX requests

前端 未结 4 1932
鱼传尺愫
鱼传尺愫 2020-11-28 08:40

I\'m working on a RESTful API of a web service on the Bottle Web Framework and want to access the resources with jQuery AJAX calls.

Using a REST client, the resource

4条回答
  •  情深已故
    2020-11-28 09:29

    Here's a minor improvement on @ron.rothman's method #2 for installing the CORS handler globally. His method requires you to specify that the OPTIONS method is accepted on every route you declare. This solution installs a global handler for all OPTIONS requests.

    @bottle.route('/<:re:.*>', method='OPTIONS')
    def enable_cors_generic_route():
        """
        This route takes priority over all others. So any request with an OPTIONS
        method will be handled by this function.
    
        See: https://github.com/bottlepy/bottle/issues/402
    
        NOTE: This means we won't 404 any invalid path that is an OPTIONS request.
        """
        add_cors_headers()
    
    @bottle.hook('after_request')
    def enable_cors_after_request_hook():
        """
        This executes after every route. We use it to attach CORS headers when
        applicable.
        """
        add_cors_headers()
    
    def add_cors_headers():
        if SOME_CONDITION:  # You don't have to gate this
            bottle.response.headers['Access-Control-Allow-Origin'] = '*'
            bottle.response.headers['Access-Control-Allow-Methods'] = \
                'GET, POST, PUT, OPTIONS'
            bottle.response.headers['Access-Control-Allow-Headers'] = \
                'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
    

    ```

提交回复
热议问题