Where is the correct place to enable CORS?

只愿长相守 提交于 2019-12-02 07:02:38

You need add this as the first line of your service implementation:

ctx.transport.resp_headers['Access-Control-Allow-Origin'] = '*'

However, that can get very annoying very fast, so here's a way to properly implement it:

class CorsService(ServiceBase):
    origin = '*'

def _on_method_return_object(ctx):
    ctx.transport.resp_headers['Access-Control-Allow-Origin'] = \
                                              ctx.descriptor.service_class.origin

CorsService.event_manager.add_listener('method_return_object', 
                                                        _on_method_return_object)

So instead of using ServiceBase, you can now use CorsService as parent class to your services to get the CORS header automatically.

Also note that it's more secure to set the header value only to the domain that hosts the Spyne service instead of using a wildcard.

No need to add any client side code.

You simply need to add the following to the header of the response sent by the server:

Access-Control-Allow-Origin: *

See http://enable-cors.org/server.html for more info for the various server setups. Not familiar with Spyne but this may help

http://spyne.io/docs/2.10/manual/06_metadata.html#protocol-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!