1. Do the front-end separation
The front end uses the Vue program, and the backend uses Django mate Rest-framework.
Then the front-end Vue through the API interface to get the data cross-domain problem, JSONP is only used in get, so use cors here to solve.
A VUE program sends a request through Ajax or Axios, which requires processing to allow cross-domain requests for resources.
Write a middleware here once and for all.
from Import Commonmiddleware
#拿到这个中间件, this middleware inherits Middlewaremixin
classCorsmiddleware (Commonmiddleware):
defProcess_response (Self,request,response):
#Add a response header #What domain name is allowed to get my data
response["Access-control-allow-origin"]="*"
#allow you to carry Content-type this request header
response["access-control-allow-headers"]="Content-type"
#allows you to send a delete request, put request
response['Access-control-allow-methods'] ="Delete,put"
returnResponse
You can also bring the middlewaremixin directly.
classMiddlewaremixin (object):def __init__(Self, get_response=None): Self.get_response=Get_response Super (middlewaremixin, self).__init__() def __call__(self, request): Response=NoneifHasattr (Self,'process_request'): Response=self.process_request (Request)if notResponse:response=self.get_response (Request)ifHasattr (Self,'Process_response'): Response=Self.process_response (Request, response)returnResponseclassCorsmiddleware (middlewaremixin):defProcess_response (self,request,response):#Add a response header #allow your domain to get my dataresponse['Access-control-allow-origin'] ="*" #allows you to carry the Content-type request headerresponse['access-control-allow-headers'] ="Content-type" #allow you to send Delete,putresponse['Access-control-allow-methods'] ="Delete,put" returnResponse
Here a cors cross-domain request is made to the response information in the middleware.
Yes, remember to add this middleware to the settings.py.
The principle of this middleware is that the browser sees this request header and does the processing
Even if you add a xxx=888 here,
This information is also visible to others through cross-domain.
The essence of Cors is to set the response header
Talk a little bit about cross-domain, Vue asks Django some questions about the data