This is the 17th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Writing in the front

Today we are going to talk about how to solve cross-domain. Before we can solve cross-domain, we should first know what cross-domain is.

What is cross-domain

Generally speaking, you enter the domain name in the browser to request resources, and there are different domain names to request other resources, this kind of different domain name request is called cross-domain.

For example, we front-end engineers enter localhost in the browser to enter the front-end project and adjust the logic, but the interface address calls the back-end API project, so cross-domain will appear.

For example, we often use Nginx to solve cross-domain (today we will focus on SpringBoot to solve cross-domain).

Nginx starts locally, such as intercepting port 80, gives intercepts, and then forwards them to the real API service

server {
        listen       80; server_name ; Location/API {proxy_pass HTTP://www.web.server/web-api/;index index.html index.htm index.jsp; }}Copy the code

For example, if we want to access the online service www.web.server/web-api, just type localhost/ API in the browser.

Ok, just a little bit about Nginx and we’ll get down to business, SpringBoot addresses several postures across domains

Implement WebMvcConfigurer

This is a classic one, probably used a lot

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // Pass all requests
        registry.addMapping("/ * *")
                // Default domain
                .allowedOrigins("*")
                // Let go of all requests
                .allowedMethods("GET"."HEAD"."POST"."PUT"."DELETE"."OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*"); }}Copy the code

Re-inject the CorsFilter

This is also relatively common

/** * resolve cross-domain */
@Configuration
public class CorsFilterConfig {


    /** * Enable cross-domain access interceptor **@date2021/4/29 will * /
    @Bean
    public CorsFilter corsFilter(a) {
        // Add the configuration after creating the CorsConfiguration object
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // Sets which raw fields to allow
        corsConfiguration.addAllowedOrigin("*");
        // Which original request headers are allowed
        corsConfiguration.addAllowedHeader("*");
        // Which requests are allowed
        corsConfiguration.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //2. Add a mapping path
        source.registerCorsConfiguration("/ * *", corsConfiguration);
        return newCorsFilter(source); }}Copy the code

Create a filter to resolve cross-domain

@Slf4j
@Component
@WebFilter(urlPatterns = { "/*" }, filterName = "headerFilter")
public class HeaderFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) resp;
        // Resolve cross-domain access error
        response.setHeader("Access-Control-Allow-Origin"."*");
        response.setHeader("Access-Control-Allow-Methods"."POST, PUT, GET, OPTIONS, DELETE");
        // Set the expiration time
        response.setHeader("Access-Control-Max-Age"."3600");
        response.setHeader("Access-Control-Allow-Headers"."Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        // Support HTTP 1.1.
        response.setHeader("Cache-Control"."no-cache, no-store, must-revalidate");
        // HTTP 1.0.response. setHeader("Expires", "0") is supported;
        response.setHeader("Pragma"."no-cache");
        / / code
        response.setCharacterEncoding("UTF-8");
        chain.doFilter(request, resp);
    }

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("Cross-domain filter start");
    }

    @Override
    public void destroy(a) {
        log.info("Cross-domain filter Destruction"); }}Copy the code

All right. So that’s all for today’s talk about how the back end resolves cross-domains and you’re welcome to comment on other solutions below

conclusion

So what we’ve talked about in the beginning is things like how the front end solves cross-domains. Let me briefly summarize a few front-end solutions to cross-domain, you can understand the following

  • 1. Cross domains through JSONP
  • Document.domain + iframe cross domain
  • 3. Location. hash + iframe
  • 4, window.name + iframe cross domain
  • 5. PostMessage crosses domains
  • 6. Cross-domain Resource Sharing (CORS)
  • 7, Nginx proxy cross domain
  • Nodejs middleware proxy across domains
  • 9. WebSocket protocol is cross-domain

Here is not a tautology, later there is time to discuss

OK. See you next time, come on!

overtones

Thank you for reading, and if you feel like you’ve learned something, you can like it and follow it. Also welcome to have a question we comment below exchange

Come on! See you next time!

To share with you a few I wrote in front of a few SAO operation

Copy object, this operation is a little SAO!

Dry! SpringBoot uses listening events to implement asynchronous operations