Cross domain access of front end and interface


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 correspondingcookieIn 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 sentcookieAnd so on,XMLHttpRequest 2An important improvement of is to provide support for credit request access.

2 solutions

2.1 cross domain issues

Because it’s still useddjangoFramework, so we use thedjango-cors-headerDo request domain audit, please check the specific usage

Thank you very much for this tool, which quickly solved the cross domain problem

2.2 cross domain request sending cookie

By defaultwidthCredentialsbyfalse, we need to setwidthCredentialsbytrue

If you are usingjquery, the calling method is as follows

   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

Cross domain access of front end and interface

Second call
Cross domain access of front end and interface

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

Recommended Today

Definition of beego routing group (namespace)

Case 1 func init(){ //Define a routing group using the namespace func //Use of routing groups: //In the outermost layer, a new routing group keyword is usually created: newnamespace //The return value is used to call addnamespace func for registration ns := beego.NewNamespace(“/v1”, //When you need to define a sub routing group again internally. Available […]