Python's Django application addresses Ajax cross-domain access

Source: Internet
Author: User
Tags install django pip install django
For the cross-domain issues that Django has encountered when writing an API for Ajax calls, let's summarize the approach that Python's Django application solves for Ajax cross-domain access issues, with the django-cors-headers of open source sharing on GitHub especially recommended

Introduction
Using Django to write an API on the server side, return a JSON data. Use Ajax to invoke the API:

<! DOCTYPE html>

However, the Chrome browser prompts for an error:

No ' Access-control-allow-origin ' header is present on the requested resource.

After Google discovered this problem is--cors caused.

What is Cors?
CORS (cross-domain resource sharing, cross-origin Resource sharing) is a cross-domain access mechanism that allows Ajax to achieve cross-domain access.
In fact, in the server response header, add "access-control-allow-origin: *" can support cors, very simple, apache/nginx and so on how to configure, see reference documentation.
As an example:

    • The API is deployed on DomainA;

    • Ajax files are deployed on DomainB, and Ajax files send requests to the API to return data;

    • Users access domainb Ajax files via DomainC, requesting data

Cross-domain access occurs in the above process. If you use Ajax directly to request it will fail, just like the chrome tip:

No ' Access-control-allow-origin ' header is present on the requested resource.

How do I troubleshoot Ajax cross-domain access issues?
To solve cross-domain problems, there are two methods: 1. Use Jsonp 2. Make cors Effective
Using the Jsonp method, you need to put the server side back into the JSONP format of response, such as Django can add JSONP related decorator, such as: http://www.php.cn/because I do not like this way, so this is skipped, You can see the references later.
Use Cors: This is easier to use, now most browsers are supported, and my web server is completely open to others to call, so it is more recommended cors.
1. Using JSONP
There are cross-domain limitations when using AJAX to get JSON data. However, it is not affected by the cross-domain to invoke the JS script file on the Web page, JSONP is to use this for cross-domain transmission. Therefore, we need to change the datatype in the AJAX call from JSON to JSONP (the corresponding API also needs to support the JSONP) format.
JSONP can only be used for GET requests.

2. Directly modify the views.py file in Django
Modify the implementation function of the corresponding API in views.py, allowing other domains to request data via Ajax:

def myview (_request):  response = HttpResponse (Json.dumps ({"Key": "Value", "Key2": "Value"}))  response[" Access-control-allow-origin "] =" * "  response[" access-control-allow-methods "] =" POST, GET, OPTIONS "  response ["access-control-max-age"] = "  response[" ("access-control-allow-headers") = "*"  return response

3. Installing Django-cors-headers
There's another discovery! In Django, someone developed the Cors-header middleware, only in settings.py to do some simple configuration, see: http://www.php.cn/now use up the server-side fully open, open cors, no cross-domain trouble, That's cool! ~
Install Django-cors-headers:

Pip Install Django-cors-headers

Added in settings.py:

Installed_apps = (...  ')  Corsheaders ',  ...) ... Middleware_classes = (...  ')  Corsheaders.middleware.CorsMiddleware ',  ' django.middleware.common.CommonMiddleware ',  ...)

You can configure a whitelist that allows cross-domain access or set it directly to allow all cross-domain access, with specific configurations to look at their GitHub page descriptions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.