Spring Boot 2.x: Don't panic when you encounter cross-domain

What is cross-domain

First, we need to understand how a URL is made up:

// Protocol + Domain Name (Subdomain + Main Domain Name) + Port Number + Resource Address

  http: + // + www.baidu.com + :8080/

As long as one of the four components of protocol, sub-domain name, main domain name and port number is different, it can be considered as different domains. Different domains access each other's resources, which is called cross-domain.

With the increasing popularity of front-end and back-end separated development, cross-domain problems are often encountered. When we see such errors in browsers, we need to be aware that cross-domain problems are encountered:

Several solutions to cross-domain problems

First, we use vue-cli to quickly build a front-end project, and then axios to send ajax requests to the background. Then print out the return information in the console. I won't go into any more details here, but I'll write a separate article later on on how to quickly create a Vue project using vue-cli.

The use of jsonp to solve cross-domain problems is not explained here, because jsonp can only pass parameters through get requests, and there are some inconveniences.

The following ways are solved by cross-domain access technology CORS(Cross-Origin Resource Sharing). We don't do any in-depth research on the concrete realization principle. The purpose of this lesson is to solve cross-domain problems.~

Method 1: Annotation

In Spring Boot, we provide an annotation @CrossOrigin to implement cross-domain, which can achieve fine-grained cross-domain control at the method level. We can add annotations to classes or parties. If we add annotations to classes, all interfaces under this class can be accessed across domains. If annotations are added to methods, then only annotated methods can be accessed.

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
   @Autowired
    private UserService userService;

   @RequestMapping("/findAll")
    public Object findAll(){
        return userService.list();
    }
}

Now let's test it again:

Bingo, success!

Method 2: Implement WebMvc Configurer

This can be achieved by implementing addCorsMappings() in the WebMvcConfigurer interface.

@Configuration
class CORSConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

Next we will comment out the annotations we just added to see if we can access the interface:

As we expected, it was all right.~

Method 3: Filter

We can solve cross-domain problems by implementing the Fiter interface and adding headers to requests:

@Component
public class CORSFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return;
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

If not unexpectedly, the return information should also be available at the console.

Nginx Configuration Solves Cross-domain Problems

If we use Nginx in our project, we can add the following configuration to Nginx to solve cross-domain problems (the principle is similar to Filter, but we just leave the work to Operations and Maintenance).

location / {
   add_header Access-Control-Allow-Origin *;
   add_header Access-Control-Allow-Headers X-Requested-With;
   add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;

   if ($request_method = 'OPTIONS') {
     return 204;
   }
}

Public Number

Originally created articles, only ignorant of learning shallow, if there is something wrong, Wangwang to inform!

Keywords: Java Vue Nginx axios Spring

Added by ricoche on Fri, 02 Aug 2019 05:20:42 +0300