Solved: No’Access-Control-Allow-Origin’ cross-domain issue

This article mainly introduces the solution: No’Access-Control-Allow-Origin’ cross-domain, the article introduces it in detail through the sample code, and has a certain reference learning value for everyone’s study or work. Friends who need it will follow Let’s study together with the editor

problem analysis:

This is a common cross-domain request problem, which is common in projects where the front and back ends are separated. The request path in the front-end project directly uses the back-end request path (for example: http://192.168.1.1:8080/demo/getUser.do), but According to the browser’s network request rules, the background server is not allowed to call directly in this way (it will be intercepted by malicious hackers). As a result, the cross-domain request was rejected (as shown below).

Access to XMLHttpRequest at’http://192.168.1.1:8080/app/easypoi/importExcelFile’ from origin’http://localhost:8080′ has been blocked by CORS policy: No’Access-Control-Allow-Origin’ header is present on the requested resource.

Solution:

Many on the Internet allow to modify the configuration files in various projects, but it is not easy to use. In fact: only need to modify a filtering configuration of the background server (such as java’s tomcat) to allow cross-domain requests;

Add the following configuration filter to the conf/web.xml configuration file of the requested server (tomcat)

(For example, when there are multiple filters in web.xml, put the following configuration at the forefront)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<filter>
 <filter-name>CorsFilter</filter-name>
 <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
 <init-param>
   <param-name>cors.allowed.methods</param-name>
   <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
 </init-param>
 <init-param>
   <param-name>cors.allowed.headers</param-name>
   <param-value>Access-Control-Allow-Origin,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
 </init-param>
 <async-supported>true</async-supported>
</filter>
<filter-mapping>
 <filter-name>CorsFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

In this way, cross-domain requests are allowed on the root (back-end), and there are also malicious injections by hackers that cause the server to be paralyzed (except for the intranet or stand-alone version).

Read More:

Leave a Reply

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