Simple build a backend project
New servlet:
The content is as follows:
package a; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Executed a cross-domain request"); response.setContentType("text/plain;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("success"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
web.xml
<servlet> <servlet-name>TestServlet</servlet-name> <servlet-class>a.TestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestServlet</servlet-name> <url-pattern>/s/t</url-pattern> </servlet-mapping>
Front-end code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <button onclick="goAjax()">ajax</button> </body> <script type="text/javascript" src="js/jquery-2.1.4.js" ></script> <script type="text/javascript"> function goAjax(){ $.ajax({ url:"http://192.168.0.102:8080/a/s/t", type:"get", success:function(data){ console.log(data); } }); } </script> </html>
Running front and back projects, an exception occurs
Checking the sending of ajax
From here, you can see that the result is returned correctly; and the background is also executed normally.
Hence the conclusion:
Cross-domain means that the browser intercepts when aja returns the result, executes it first, and then judges it, not the background does not allow cross-domain;
The client creates an img tag, the address is the ajax address just now
<img src="http://192.168.0.102:8080/a/s/t" />
View request
View the request, still successful.
Conclusion: Cross-domain only occurs on the xmlHttpRequest object, and in layman's terms, it happens on ajax.
The browser parses the host information of our ajax request from our request path, and knows that it is a cross-domain request, and adds an origin header to the request header.
We can add a response header when returning to intercept cross-domain through the browser.
1. Realize cross-domain by modifying the background code
Add filter CrossFilter.java
package a; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CrossFilter implements Filter{ @Override public void destroy() {} @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain doChain) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest) req; HttpServletResponse response=(HttpServletResponse)res; request.setCharacterEncoding("utf-8"); //response.setContentType("text/plain;charset=utf-8"); //response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8020");或者 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "*");//GET POST //response.setHeader("Access-Control-Allow-Headers","content-type"); //跨域预检缓存 response.setHeader("Access-Control-Max-Age","3600"); doChain.doFilter(req,res); } @Override public void init(FilterConfig arg0) throws ServletException { } }
web.xml
<filter> <filter-name>CrossFilter</filter-name> <filter-class>a.CrossFilter</filter-class> </filter> <filter-mapping> <filter-name>CrossFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Cross-origin requests are now possible.
Simple request:
1.get,head,post
2. In the request header
1) No custom header
2) Content-Type is the following: text/plain, multipart/form-data, application/x-www-form-urlencoded.
non-simple request
1. Ajax request of put and delete methods
2. Send ajax request in json string format
3. Ajax request with custom header
When ajax sends a non-simple request, the request will fail
$.ajax({ url:"http://192.168.0.102:8080/a/s/t", type:"post", contentType:"application/json", data:JSON.stringify({name:"gys"}), success:function(data){ console.log(data); } });
Combined with the above tips, we add a header to the filter.
Re-run, the cross-domain problem is solved, and when looking at the request, it is found that an ajax request is sent to both sides.
The first is a preflight request, which checks whether a cross-domain request can be passed when a non-simple request occurs.
If each request is pre-checked like this, it will consume a lot of network resources and affect our request speed.
A preflight cache can be added on the filter side.
Now only the preflight request will appear when the first request is made, and there will be no subsequent ones.
But now I want to restore the preflight request and annotate the preflight code, but it has not reached the cache time of the preflight request, and there is no way to view the preflight request.
You can check Disable cache of Google Chrome
Come back at night to continue writing the following content
nginx forwarding to achieve cross-domain
The configuration of nginx responds to the proxy to achieve cross-domain.