Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Preface: YESTERDAY, I met a cross-domain problem in project deployment. Today, I will make up for my solution and curiosity at that time.

Cross-domain around: during my work, I often hear people around me mention cross-domain problems. In my mind, the first thing that comes to mind is vUE reverse proxy to solve cross-domain problems, server setting permissions, nGINx request header control, etc.

For vUE cross-domain we can use the following way to solve (proxyTable) :

The standard project for vUE scaffold generation shall prevail here. There is usually an index file under the project config directory.

const path = require('path')

module.exports = {
    dev: {
        // Paths
        assetsSubDirectory: 'static',
                assetsPublicPath: '/',
                proxyTable: {
            '/sys':{
                target:'http://localhost:9002',
                        changeOrgin:true,
                        pathRewrite:{
                    '^/sys':'/sys'
                }
            }
        },
        host: 'localhost',
                port: 8888,
                autoOpenBrowser: false,
                errorOverlay: true,
                notifyOnErrors: false,
                poll: false,
                useEslint: true,
                showEslintErrorsInOverlay: false,
                devtool: '#cheap-source-map',
                cacheBusting: true,
                cssSourceMap: false,
    },
Copy the code

For servers such as JAVA we can use the above mentioned processing as follows:

Method 1: Filter)


public class SimpleCORSFilter implements Filter{

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}
Copy the code

Write to web.xml

<filter>
<filter-name>cors</filter-name>
<filter-class>com.ssm.web.filter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>  
    </filter-mapping>
</filter>
Copy the code

Where you can also provide cross-domain HttpServletResponse for individual actions as follows:

response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
Copy the code

Method 2:

Solution in SpringBoot

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * Implement cross-domain request * @author ** / @configuration public class CorsConfig {@bean public CorsFilter CorsFilter () {final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); final CorsConfiguration corsConfiguration = new CorsConfiguration(); / * whether to allow the request with authentication information * / corsConfiguration setAllowCredentials (true); / * allows access to the client domain name * / corsConfiguration addAllowedOrigin (" * "); / * allows server access client request header. * / corsConfiguration addAllowedHeader (" * "); / * allows access to the method name, GET POST etc. * / corsConfiguration addAllowedMethod (" * "); urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(urlBasedCorsConfigurationSource); }}Copy the code

Resolving cross-domains in Nginx:

Method 1: Reverse proxy

server { listen 80; server_name localhost; location /Api { proxy_pass http://localhost:8080/Api; index index.html index.htm; }}Copy the code

Method 2: Control the request header

location / { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; if ($request_method = 'OPTIONS') { return 222; }}Copy the code

Supplement: Met yesterday the problem is that I didn’t think of, when screening for 5 minutes is TOMCAT1.9 cross-domain problem, is, after all, he hadn’t heard of the term, was also his own speculation, didn’t expect to find some information on the Internet, really have this kind of solution, the oneself try holding the attitude and certain theoretical reasoning to practice, That’s the question.

The solution to TOMCAT1.9 is to insert the following code in the estimated 400 lines of web.xml in the conf file:

<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</filter>
Copy the code

These are my cross-domain problems and solutions. Feel free to leave a comment in the comments section if there are other ways!