Solution to Nginx cross-domain problem

Project scenario:

Web front-end development often encounters cross-domain access. If there is no way to allow the background to open access domains, the calling interface will be blocked by the browser. As a solution to cross-domain problems, you can build a background service for intermediate forwarding, or use nginx icon-default.png?t=N176https://so.csdn.net/so/search?q=nginx to forward.

Problem Description

The problem occurs in nginx reverse proxy icon-default.png?t=N176https://so.csdn.net/so/search?q=%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86 springboot backend When applying, a Cros error occurs when the front end requests the back end, as shown in the figure below.

Cause Analysis:

1. As a proxy service, Nginx needs to be configured to allow cross-domain

2. Springboot background service needs to be configured to allow cross-domain requests

solution:

1. Check whether the background service is set to allow cross-domain, the setting method is as follows:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("Content-Type","X-Requested-With","accept,Origin","Access-Control-Request-Method","Access-Control-Request-Headers","token")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowCredentials(true);
    }
 
    /**
     * 支持PUT、DELETE请求
     */
    @Bean
    public FormContentFilter httpPutFormContentFilter() {
        return new FormContentFilter();
    }
 
}

2. Check whether the nginx.conf configuration file allows cross-domain, and configure it in the server configuration. The configuration method is as follows:

    location /space-time/ {
      if ($request_method = OPTIONS ) {
        add_header Access-Control-Allow-Origin "*" always;
        add_header Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE";
        add_header Access-Control-Max-Age "3600";
        add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization";
        add_header Content-Length 0;
        add_header Content-Type text/plain;
        return 200;
      }

      proxy_set_header Content-Type application/json;
      add_header Access-Control-Allow-Origin "*" always;
      add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
      add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";

      proxy_pass http://localhost:8086/space-time/;
      proxy_set_header X-Real-IP $remote_addr;

    }

Guess you like

Origin blog.csdn.net/Angel_asp/article/details/129014335