preface

This article will explain common solutions to cross-domain problems in front and back end projects, where the back end is based on SpringBoot and the front end uses jQuery, AXIos and other frameworks to explain the actual code. This article will not cover cross-domain interpretation and frameworks like SpringBoot, or the use of Nginx. It will focus on cross-domain problem solving in front and back end separation projects, but if you encounter problems, you are welcome to learn together.

Cross-domain solutions

  • The json approach

    This method can only be used for Get requests, so if you need to obtain data in Post request mode, you can first look at the following CORS solution. Here are two solutions based on JSONP principle, first look at the backend interface:

    @RestController
    @RequestMapping("/api/customer")
    public class HelloController {
    
        @GetMapping("/getAllCustomerInfo")
        public String getAllCustomerInfo(a) {
            // The returned data must be contained in the getAllCustomerInfo() string
            // So that when you return to the front end, you can automatically execute the callback function to get the data
            // getAllCustomerInfo() corresponds to the name of the front-end callback function
            return "getAllCustomerInfo(" + getCustomerList() + ")";
        }
    
        private String getCustomerList(a) {
            List<Customer> list = new ArrayList<>(Arrays.asList(
                    new Customer(1."Zhang"."123456"),
                    new Customer(2."Bill"."654321"),
                    new Customer(3."Fifty"."123123")));return newGson().toJson(list); }}Copy the code

    The following two solutions are explained:

    1. Js native solution

      // First set SRC and add the node to 
      const script = document.createElement('script')
      script.src = 'http://localhost:8080/api/customer/getAllCustomerInfo'
      document.head.appendChild(script)
      
      // The callback function name corresponds to the name returned in the interface
      const getAllCustomerInfo = res= > {
      	console.table(res, ['id'.'username'.'password'])}Copy the code

      With the above Settings, you can see the following results on the Console:

    2. JQuery ajax solution

      // Remember to introduce jQuery
      <script src="https://cdn.staticfile.org/jquery/1.10.0/jquery.js"></script>
      
      $.ajax({ 
      	url: 'http://localhost:8080/api/customer/getAllCustomerInfo'.type: 'get'.dataType: 'jsonp'.jsonpCallback: "getAllCustomerInfo"
      })
      
      // Same as above
      const getAllCustomerInfo = res= > {
      	console.table(res, ['id'.'username'.'password'])}Copy the code
  • CORS solutions

    Cross-domain resource sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to allow Web applications running on one Origin (domain) to access specified resources from different source servers. When a resource requests a resource from a different domain, protocol, or port than the server on which the resource itself resides, the resource makes a cross-domain HTTP request, as explained in the link.

    1. On the back-end interface

      In this case, we use AXIos. Before we show the back-end code, let’s take a look at the changes to the back-end code. In order to differentiate JSONP from JSONP which can only do Get requests, we change the interface to Post:

      @RestController
      @RequestMapping("/api/customer")
      public class HelloController {
      
          @PostMapping("/getAllCustomerInfo")
          public List<Customer> getAllCustomerInfo(HttpServletResponse response) {
              // Set the response header
              response.setHeader("Access-Control-Allow-Origin"."*");
              // You no longer need to put the result in the callback function
              return new ArrayList<>(Arrays.asList(
                      new Customer(1."Zhang"."123456"),
                      new Customer(2."Bill"."654321"),
                      new Customer(3."Fifty"."123123"))); }}Copy the code

      The front-end code then uses the Ajax request directly:

      // We need to introduce axios first
      <script src="https://cdn.staticfile.org/axios/0.1.0/axios.js"></script>
      
      axios.post('http://localhost:8080/api/customer/getAllCustomerInfo')
      	.then(res= > {
      		console.table(res, ['id'.'username'.'password'])})Copy the code
    2. Nginx reverse proxy

    Reverse proxy knowledge is not explained in detail here, if you are interested, you can check out this link. By using Nginx’s reverse proxy, we can remove the code setting of the response header from the backend interface:

    @RestController
    @RequestMapping("/api/customer")
    public class HelloController {
    
        @PostMapping("/getAllCustomerInfo")
        public List<Customer> getAllCustomerInfo(a) {
            return new ArrayList<>(Arrays.asList(
                    new Customer(1."Zhang"."123456"),
                    new Customer(2."Bill"."654321"),
                    new Customer(3."Fifty"."123123"))); }}Copy the code

    Then there are the changes in nginx.conf:

    server {
    	Port 8080 = port 8080 = port 8080
        listen       80;
        server_name  localhost;
    
        location / {
            root   html;
            # add head
            add_header Access-Control-Allow-Origin *;
            The proxy forwards to port 8080proxy_pass http://localhost:8080; index index.html index.htm; }}Copy the code

    Then change the interface accessed in the front-end to 80:

    // We need to introduce axios first
    <script src="https://cdn.staticfile.org/axios/0.1.0/axios.js"></script>
    
    // 80 is the default HTTP port and can be omitted
    axios.post('http://localhost/api/customer/getAllCustomerInfo')
                 .then(res= > {
                    console.table(res, ['id'.'username'.'password'])})Copy the code

    Then start the Nginx server, and the Console again shows what we want to see:

    ! [image-20200915150523876](//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7e9a8d8d20f44347b5aaed5fa090030d~tplv-k3u1fbpfcp-z oom-1.image)Copy the code

conclusion

This article does not include all solutions to cross-domain problems, but it is believed that most of them can be solved. This article may be updated in the future to explain more ways to solve cross-domain problems, and you are welcome to exchange and learn together.