Cross-domain (CORS) issues are encountered when requesting data from another domain by XHR (xmlhttprequest) in a browser.Cors:cross-origin Resource Sharing
What is cross-domain?
Simply put, for security reasons, JavaScript in a browser page cannot access data on other servers, the same-origin policy. Cross-domain is a means to bypass the same-origin policy restrictions, to achieve communication between different servers.
Workaround:
The basic solution is to use the filter to add a head "Access-control-allow-origin" to the response, such as :
Response.setheader ("Access-control-allow-origin", "*"); Allow all requests Response.setheader ("Access-control-allow-origin", "http://www.baidu.com:80"); Allow only requests from http://www.baidu.com:80, separated by commas
Specific solutions:
1. custom filter, add header to response in filter: ("Access-control-allow-origin", "*")
How to add a filter:http://blog.csdn.net/clementad/article/details/46763669
/** * Prevent browser cache page or request result * @author Xujijun * */public class Nocachefilter implements Filter {@Overridepublic void Destroy () {}@ overridepublic void DoFilter (ServletRequest req, Servletresponse resp, Filterchain chain) throws IOException, servletexception { HttpServletResponse response = (httpservletresponse) resp; Response.setdateheader ("Expires",-1); Response.setheader ("Cache_control", "No-cache"); Response.setheader ("Pragma", "No-cache"); Response.setheader ("Access-control-allow-origin", "*"); Allow cross-domain request chain.dofilter (req, resp);} @Overridepublic void init (Filterconfig arg0) throws servletexception{}}
result diagram:
or use a third-party package:2, http://software.dzhuvinov.com/cors-filter.html
3, Https://github.com/eBay/cors-filter
or search for "cors filter" on Mvnrepository: Http://mvnrepository.com/search?q=cors-filter
Deprecated Workaround: JSONP
What is JSONP?
JSON (JavaScript Object Notation) is a lightweight data interchange format, while JSONP (JSON with Padding) is a "usage pattern" of JSON that enables cross-domain acquisition of data.
Under the same-Origin policy, a page under a server cannot get data outside of that server, except that tags such as IMG, IFRAME, script, and so on, can be used to request data on other servers through the SRC attribute. Using the script tag's open strategy, we can implement cross-domain request data, of course, also need the service side of the cooperation. When we normally request a JSON data, the server returns a string of JSON-type data, and when we use the JSONP mode to request data, the server returns an executable JavaScript code .
Reference article: Cors specification: Http://www.w3.org/TR/cors/XMLHttpRequest:https://en.wikipedia.org/wiki/XMLHttpRequest
(original article, reprint please specify the CSDN blog from Clement-xu )
Copyright NOTICE: This article is the original article, reprint please indicate the CSDN blog which is transferred from Clement-xu.
Cross-domain (CORS) issues with Ajax requests