Causes and solutions to cross-domain problems

Cross-domain issues

  • What is cross-domain?

    When calling third-party interfaces, cross-domain problems will occur. This is the same-origin policy of the browser.
    1. Because the domain name of the requesting party is different, the requested interface is considered to be of non-original origin.
    2. At the same time, for security reasons, browsers limit cross-origin HTTP requests initiated within scripts. For example, the XMLHttpRequest and Fetch APIs follow the same-origin policy. Therefore, related requests reported cross-domain errors.

  • Server-side solution using CORS:

    The solution from the server side is CORS. CORS is a W3C standard, whose full name is “Cross-origin resource sharing”. Some judgments are made (is the requesting party in its own “white list”?). If there is no problem, the data will be returned, otherwise it will be rejected. In the following example, code is added to Java Spring to solve cross-domain problems.

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping(“/**”)
    .allowedOriginPatterns(“*”)
    .allowedMethods(“POST”, “GET”, “PUT”, “OPTIONS”, “DELETE”)
    .maxAge(3600)
    .allowCredentials(true);
    }
    }

  • Server-side solution using Nginx:

    location /api/ {
    add_header ‘Access-Control-Allow-Origin’ $http_origin;
    add_header ‘Access-Control-Allow-Credentials’ ‘true’;
    add_header ‘Access-Control-Allow-Methods’ ‘GET, POST, OPTIONS’;
    add_header ‘Access-Control-Allow-Headers’ ‘DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range’;
    add_header ‘Access-Control-Expose-Headers’ ‘Content-Length,Content-Range’;
    if ($request_method = ‘OPTIONS’) {
    add_header ‘Access-Control-Max-Age’ 1728000;
    add_header ‘Content-Type’ ‘text/plain; charset=utf-8’;
    add_header ‘Content-Length’ 0;
    return 204;
    }
    proxy_pass http://apiserver/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_connect_timeout 5;
    }

  • Other way: Use the same domain name

    The caller and all called interfaces are placed in the same domain name

  • Other way : UseJSONP,WebSockets, etc.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *