Django's middleware to solve the problem before and after the end of the same origin policy

Problem Description

Front-end time in the company, to develop a website using angular, because it is suitable angular separation of the front and rear end, so we made a simple library management system to simulate the front and rear ends of the splitter.

But in the development process to meet the problem of cross-domain origin policy, the page can be displayed, but no data is shown below

Right-check given as follows:

Code is given below

Failed to load http://127.0.0.1:8888/publisher/: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:4200' is therefore not allowed access.

 

angular data is acquired from the rear end of the code as follows:

private publishersUrl = 'http://127.0.0.1:8888/publisher/';
private addpubUrl = 'http://127.0.0.1:8888/addpub/';


getPublishers (): Observable<Publisher[]> {
    return this.http.get<Publisher[]>(this.publishersUrl)
    .pipe(
      catchError(this.handleError<Publisher[]>('getPublishers', []))
    ); 
}

problem causes

This problem occurs because cross-domain origin policy issue, not discussed here in detail on this issue, who are interested can go to search.

 

problem solved

The key is to solve this problem the rear end, to allow access to other sites, where we can define a middleware to solve this problem, the following steps.

1. Create a new file in the myMiddleware.py app.

2. Add the following code in the file

from django.utils.deprecation import MiddlewareMixin


class MyCore(MiddlewareMixin):
    def process_response(self, request, response):
        response['Access-Control-Allow-Origin'] = "*"
        if request.method == "OPTIONS":
            # 复杂请求 预检
            response['Access-Control-Allow-Headers'] = "Content-Type"
            response['Access-Control-Allow-Methods'] = "POST, DELETE, PUT"
        return response

3. go to settings file registered middleware

MIDDLEWARE = [
    'BMS.myMiddleware.MyCore',
]

 

Thus, even if the problem is resolved, we will look at the results of the project up and running

 

Guess you like

Origin www.cnblogs.com/yifchan/p/python-1-32.html