Home > Article > Web Front-end > Two solutions to Ajax cross-domain issues
ajax itself actually interacts with data through the XMLHttpRequest object. However, for security reasons, the browser does not allow js code to perform cross-domain operations and will issue a warning, so the ajax cross-domain problem occurs.
Overview
Ajax cross-domain is a common problem in front-end development. This article describes the case where Google browser Chrome is used as the client and Tomcat is used as the web server. solution.
Problem phenomenon
When cross-domain access occurs, ajax will usually report an error similar to the following:
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:8000' is therefore not allowed access.
Solution 1: Turn off the browser's cross-domain security settings, only for testing during development
Take the chrome browser as an example, right-click the chrome shortcut, and then Append --disable-web-security after the Target value. Note that there is a space before --. For example:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security
After starting, the Chrome browser will prompt you "You are using an unsupported command line flag: --disable-web-security", says it is not safe and therefore limited to testing.
In this way, you can test directly without cross-domain errors!
Solution 2: Configure the Web server to support cross-domain access
Here is a solution for using Tomcat as the Web server, in the WEB-INF of the Java Web program Just add the following configuration to the web.xml file under.
<!--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 below org.apache.catalina.filters.CorsFilter. If there is no configuration above, the system's default configuration will be used. In the actual production environment, configuration should be performed as needed to improve security. For example, cors.allowed.origins configures the source addresses allowed to be accessed. The default is all, that is, *. In addition, there are cors.allowed.methods, cors.allowed.headers and so on. For specific configuration details, please see [1] in the references of this article.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Click to load based on ajax More loading without refreshing to this page
How to solve ajax Invalid on Google Chrome browser
How to use jQuery post to pass data containing special characters
The above is the detailed content of Two solutions to Ajax cross-domain issues. For more information, please follow other related articles on the PHP Chinese website!