Detailed graphic and text explanation of how to handle cross-domain request error issues in Python's bottle framework

高洛峰
Release: 2017-03-20 09:14:57
Original
1659 people have browsed it

This article mainly introduces the bottle framework of python How to deal with cross-domain request error reporting. Friends in need can refer to it

Using python When developing the bottle framework, when the front-end uses ajax for cross-domain access, the js code always fails to enter success, but enters error, and the returned status is 200. It is normal to access the url directly in the browser. After pressing F12 in the browser, you will find the following error message

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.

If you query errors through search engines, you will find that almost all the answers you find are cross-domain problems. You only need to add the following to the code of the main file. Many solutions on foreign websites explain this

@hook('after_request')
def enable_cors():
 response.headers['Access-Control-Allow-Origin'] = '*'
Copy after login

In fact, after adding according to the found solution, an error still occurred. Looking at the http header output by the browser, we did not see the Access-Control-Allow-Origin:* we just added, as shown below:

Through DEBUG, enter the bottle source code to view

I have tested that this problem exists in the bottle framework corresponding to python2 and python3 For this problem, we change it to:


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
Copy after login


When you run the code again, you can see that the ajax code is normal


The above is the detailed content of Detailed graphic and text explanation of how to handle cross-domain request error issues in Python's bottle framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template