在用python的bottle框架开发时,前端使用ajax跨域访问时,js代码老是进入不了success,而是进入了error,而返回的状态却是200。url直接在浏览器访问也是正常的,浏览器按F12后会发现下面这个错误提示
XMLHttpRequest cannot load http://192.168.0.118:8081/get_mobile_number/?id=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
通过搜索引擎查询错误,会发现几乎查找出来的答案都说是跨域问题,只需要在主文件的代码中添加下面就可以了,国外的网站好多解决方案都是这样说明
@hook('after_request') def enable_cors(): response.headers['Access-Control-Allow-Origin'] = '*'
class HTTPResponse(Response, BottleException): def init(self, body='', status=None, headers=None, **more_headers): super(HTTPResponse, self).init(body, status, headers, **more_headers) def apply(self, response): response._status_code = self._status_code response._status_line = self._status_line if self._headers: if response._headers: response._headers.update(self._headers) else: response._headers = self._headers response._cookies = self._cookies response.body = self.body
再运行代码就可以看见ajax代码正常了
以上就是图文详解python的bottle框架跨域请求报错问题的处理方法的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于图文详解python的bottle框架跨域请求报错问题的处理方法的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did82586