關於python的bottle架構跨域請求報錯問題的處理,pythonbottle

來源:互聯網
上載者:User

關於python的bottle架構跨域請求報錯問題的處理,pythonbottle

  在用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'] = '*'

  而事實上是按找出來的解決方案添加後還是出現錯誤,查看瀏覽器輸出的http頭並沒有看到我們剛剛增加的Access-Control-Allow-Origin:*,如:

 

  通過DEBUG,進入bottle的源碼中查看

 

  這個問題我測試過在python2與python3對應的bottle架構中都存在這種問題,我們將它改為:

 

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代碼正常了

 

 

 著作權聲明:

  本文由AllEmpty原創並發佈於部落格園,歡迎轉載,未經本人同意必須保留此段聲明,且在文章頁面明顯位置給出原文連結,否則保留追究法律責任的權利。如有問題,可以通過1654937@qq.com 聯絡我,非常感謝。

 

  發表本編內容,是為了和大家共同學習共同進步,有興趣的朋友可以加加Q群:327360708 ,大家一起探討。

    更多內容,敬請觀注部落格:http://www.cnblogs.com/EmptyFS/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.