Two solutions to Ajax cross-origin problems: ajax cross-origin Solutions
Overview
Ajax cross-origin is a common problem in front-end development. This article describes the solutions when Google Chrome is used as the client and Tomcat is used as the Web server.
Symptom
When cross-origin access occurs, ajax usually reports the following error:
XMLHttpRequest cannot load http: // 192.168.2.12: 8001/oss/api/version/check. no 'access-Control-Allow-origin' header is present on the requested resource. origin 'HTTP: // localhost: 100' is therefore not allowed access.
Solution 1: Disable the cross-origin security settings of the browser, which is only used for testing during development.
Take chrome as an example. Right-click the chrome shortcut and append -- disable-web-security after the Target value. Note that there is a space in front. For example:
"C: \ Program Files (x86) \ Google \ Chrome \ Application \ chrome.exe" -- disable-web-security
After it is started, Chrome will prompt you that "you are using an unsupported command line flag: -- disable-web-security", which is not safe, so it is limited to testing.
In this way, you can directly test without cross-origin errors!
Solution 2: configure the Web server to support cross-origin access
Here is the solution to Tomcat as the Web server, add the following configuration in the Web. xml file under the WEB-INF of Java web program.
<!--cors filter--> <filter> <filter-name>CorsFilter</filter-name> <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Note: There are several configuration options under org. apache. catalina. filters. CorsFilter. If no configuration is set above, the default configuration of the system is used. In the actual production environment, you need to configure as needed to improve security. For example, if cors. allowed. origins is configured as the allowed source address, the default value is all, that is *. In addition, there are cors. allowed. methods, cors. allowed. headers, and so on. For detailed configuration details, see [1] In the references in this article.
The above two methods can solve the cross-origin issue of ajax. I hope this article will help you.