There are three main solutions to the problem of Ajax cross-domain problems
1. Use the proxy to mount the Cross-domain address below the domain
2. Use Jsonp
3. Use Access-control-allow-origin response Head
The first solution needs to introduce proxy server, production environment generally use Nginx or Apache HTTP to do load balancing, can be easily implemented, their development environment generally do not have this thing, need to introduce, increase the complexity
The second scenario needs to modify the returned data, and the response of the Cross-domain request needs to be encapsulated into the format of the callback (' {A: ' B '} ')
The third is that the new features introduced by the Global Consortium to address cross-domain problems (as if introduced by HTML5), are currently supported by most new browsers, and can be implemented across domains by adding access-control-allow-origin to the response header
springmvc4.2 begins to provide out-of-the-box cross-domain support by adding the following code to the MVC configuration file, detailed configuration reference to the official documentation
<mvc:annotation-driven/>
<mvc:cors>
<mvc:mapping path= "/**"/>
</mvc:cors>
Note that you must add <mvc:annotation-driven/>, previously used a custom requestmapping, did not use <mvc:annotation-driven/> caused cross-domain failure, after debugging to discover, If there is no <MVC:ANNOTATION-DRIVEN/>,MVC to get the Cors configuration information
By default, Ajax Cross-domain requests do not carry cookies, and sometimes we need cookies to join Cross-domain authentication support
<mvc:annotation-driven/>
<mvc:cors>
<mvc:mapping path= "/rest/**"
Allowed-origins= "http://localhost"
Allow-credentials= "true"/>
</mvc:cors>
The Allow-credentials=true representative opens Cross-domain authentication, which adds a response header Access-control-allow-credentials:true
Allowed-origins represents a domain name that can be requested across domains, where it is important to note that if Cross-domain authentication support is added, Allowed-origins must be an explicit domain name and cannot use the "*" wildcard character
The browser receives this response header. The client also needs to set the XMLHttpRequest withcredentials flag to True
Xhr.withcredentials=true
jquery down for
$.ajax ({
URL: ' Data/tree.json ',
Xhrfields: {
Withcredentials:true
}
});
The next request will take the cookies with you.