1 business scenario
-
In the current product development, the front-end and back-end are completely separated. In the debugging stage, the ports of the static server and the interface server are different. When the front-end and back-end communicate, cross domain processing is needed here, which can be processed by the back-end.
-
When the user calls the interface for the first time, the back end sets the corresponding
cookie
In the second call, when we ask the front end to call the interface, we will send the cookie set in the first call. By default, standard cross domain requests are not sentcookie
And so on,XMLHttpRequest 2
An important improvement of is to provide support for credit request access.
2 solutions
2.1 cross domain issues
Because it’s still useddjango
Framework, so we use thedjango-cors-header
Do request domain audit, please check the specific usagehttps://github.com/ottoyiu/django-cors-headers
Thank you very much for this tool, which quickly solved the cross domain problem
2.2 cross domain request sending cookie
By defaultwidthCredentials
byfalse
, we need to setwidthCredentials
bytrue
If you are usingjquery
, the calling method is as follows
$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
});
3 examples:
Back end business: for example, get list interface (using Django rest framework)
def list(self, request, *args, **kwargs):
instance = super(ManufacturerView, self).list(request, *args, **kwargs)
instance.set_cookie('uuid', 'fkajdflksduiwerw')
return instance
First call
Second call
Here I take the clever, directly ignore the referer can, the next will be modified
4 Summary
In this way, the problem of front-end and back-end completely isolated communication is simply solved. According to the needs of the business, the design meets the needs of their own business