On the cross domain problems of django rest jwt vue

  • 2021-01-02 21:55:51
  • OfStack

When using router to register url, the error of accessing interface package 302 May be due to the request for url writing.

If you request /api/login/ report 302, you need to remove the backslash and write /api/login request cross-domain correctly:

Cross domain:

Simply put, the javascript code for the A site attempts to access the B site, including submitting and retrieving content. This is clearly not safe. For this reason, the father of the browser, Netscape (Netscape), came up with an excellent solution: the famous browser same-origin policy. All browsers that support JavaScript now use this strategy.

The same:

Sites with the same domain name, protocol, and port are considered homologous.

Process:

When two Tab pages of a browser open baidu page and Google page respectively, baidu initiates a script execution, at which time the browser will check which page the script belongs to. That is, check for homology. Only scripts that have the same origin as Baidu will be executed. If not same-origin, the browser reports an exception to the console when requesting data. Prompt denial of access.

Solutions:

Install django cors -- headers


 pip install django-cors-headers

settings. py configuration


 INSTALLED_APPS = [

  ...

  "corsheaders" . 

...

]

 

MIDDLEWARE_CLASSES = (

  ...

"corsheaders.middleware.CorsMiddleware",

"django.middleware.common.CommonMiddleware", #  Note that the order 

...

)

#  Increase neglect across domains 

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

CORS_ORIGIN_WHITELIST = (

  "*"

)

 

CORS_ALLOW_METHODS = (

  "DELETE",

  "GET",

  "OPTIONS",

  "PATCH",

  "POST",

  "PUT",

  "VIEW",

)

 

CORS_ALLOW_HEADERS = (

  "XMLHttpRequest",

  "X_FILENAME",

  "accept-encoding",

  "authorization",

  "content-type",

  "dnt",

  "origin",

  "user-agent",

  "x-csrftoken",

  "x-requested-with",

)

To solve

With the above configuration, the django cross-domain request processing is perfectly solved.

It should be noted that THE middleware of cors-ES53en, CorsMiddleware, must be placed before the middleware of ES55en-ES56en when registered.


Related articles: