Solve the problem of the browser same-origin policy DRF project

DRF project, the end of the separation is a Web front frame.

In this project, we used a front-end framework for VUE.

Separate front and rear ends where a problem occurs, Ajax request to the front end of the rear end can not request API (Interface).

So why is there such a problem?

Because the browser's same-origin policy does not allow scripts for different sources (website code Ajax) without the explicit authorization under the circumstances, to read and write each other's resources.

As mentioned in the same-origin policy, we can not avoid the need to understand what is at once the source , what is also called homologous origin policy .

Source: url refers to the protocol, the domain name, port number;

Homologous: url when two protocols, domain names, port numbers are the same, then we call this url is two homologous.

Same Origin Policy: Refers to a security function of the browser, and its role is to allow two non-homologous url prevent communication.

Now, we have identified the problem, then we will begin to solve the problem.

Here, we need to use to achieve cross-domain url between non-homologous to communicate.

We use cross-domain approach is cross-domain resource sharing CORS (Cross-Origin Resource Sharing) .

Now, we know that the way to solve the problem, then we will have to use the code to achieve.

First, we need to install third-party module, with Django program CORS configuration.

pip install django-cors-headers

Then, we need to project configuration file to configure.

INSTALLED_APPS = [
    ...

    # Sign CORS cross-domain access sub-applications 
    ' corsheaders ' ,

]
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    ...
]

Here, the required configuration request whitelist.

# CORS
CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1:8080',
    'http://localhost:8080',
    'http://www.meiduo.site:8080',
    'http://www.meiduo.site:8000'
)
CORS_ALLOW_CREDENTIALS = True   # allowed cookie

When we completed the above operation, we get rid of the same-origin policy issues browsers friends.

Guess you like

Origin www.cnblogs.com/chao666/p/12300056.html